{"record":{"id":"8499fe9ec31a96b6","repo":"krahets/hello-algo","slug":"error-8499fe","errorCode":null,"errorMessage":"队列为空","messagePattern":"队列为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb","lineNumber":55,"sourceCode":"      @rear.next = node\n      @rear = node\n    end\n\n    @size += 1\n  end\n\n  ### 出队 ###\n  def pop\n    num = peek\n    # 删除头节点\n    @front = @front.next\n    @size -= 1\n    num\n  end\n\n  ### 访问队首元素 ###\n  def peek\n    raise IndexError, '队列为空' if is_empty?\n\n    @front.val\n  end\n\n  ### 将链表为 Array 并返回 ###\n  def to_array\n    queue = []\n    temp = @front\n    while temp\n      queue << temp.val\n      temp = temp.next\n    end\n    queue\n  end\nend\n\n### Driver Code ###\nif __FILE__ == $0","sourceCodeStart":37,"sourceCodeEnd":73,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb#L37-L73","documentation":"Raised by `LinkedListQueue#peek` (linkedlist_queue.rb:55) when `is_empty?` is true. The method reads `@front.val`; on an empty queue `@front` is nil, so the guard prevents a NoMethodError. The `pop` method delegates to `peek`, so dequeueing an empty queue also triggers this.","triggerScenarios":"Calling `queue.peek` or `queue.pop` when the linked list has no nodes (`@size == 0`). Occurs after consuming all elements or before the first enqueue.","commonSituations":"BFS frontier fully drained then peeked; consumer loop that pops past empty; queue shared across threads where one drains before the other peeks.","solutions":["Guard with `unless queue.is_empty?` before `peek` or `pop`.","Drive the consumer with `while queue.size > 0`.","Rescue IndexError if an empty peek is recoverable."],"exampleFix":"# before\nhead = queue.peek\n\n# after\nhead = queue.is_empty? ? nil : queue.peek","handlingStrategy":"validation","validationCode":"return nil if queue.is_empty?\nqueue.peek","typeGuard":"def ll_queue_readable?(queue)\n  queue.respond_to?(:is_empty?) && queue.respond_to?(:peek) && !queue.is_empty?\nend","tryCatchPattern":"begin\n  queue.peek\nrescue IndexError\n  nil\nend","preventionTips":["Check is_empty? before peek or pop.","In BFS, check frontier emptiness before peeking.","Use while queue.size > 0 as the consumer loop bound."],"tags":["ruby","queue","linked-list","precondition","empty-state"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}