{"record":{"id":"0aa65ef4d73c613b","repo":"krahets/hello-algo","slug":"error-0aa65e","errorCode":null,"errorMessage":"佇列為空","messagePattern":"佇列為空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"zh-hant/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/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb#L37-L73","documentation":"Raised by the peek method of the LinkedListQueue teaching class (a singly-linked-list FIFO queue) when is_empty? is true. It guards @front.val so you never dereference a nil front pointer. Note that pop calls peek internally, so dequeuing an empty queue also propagates this error.","triggerScenarios":"Calling queue.peek or queue.pop on a newly constructed queue, calling them after all elements were dequeued, or draining past empty in a loop.","commonSituations":"Consumer reading faster than producer enqueues; peeking before any push; using a fixed-count drain loop instead of while !is_empty?.","solutions":["Check queue.is_empty? before calling peek or pop.","Return nil when empty: queue.is_empty? ? nil : queue.peek.","Use while !queue.is_empty? for safe draining.","Track enqueue/dequeue counts to catch imbalances."],"exampleFix":"# before\nval = queue.peek  # raises on empty queue\n\n# after\nval = queue.is_empty? ? nil : queue.peek","handlingStrategy":"validation","validationCode":"return nil if queue.is_empty?\nqueue.peek","typeGuard":"# Ruby: safe peek\ndef safe_peek(queue)\n  queue.is_empty? ? nil : queue.peek\nend","tryCatchPattern":"begin\n  head = queue.peek\nrescue IndexError\n  head = nil\nend","preventionTips":["Check is_empty? before peek or pop (pop calls peek internally).","Use 'while !queue.is_empty?' to drain.","This prevents a nil.val NoMethodError on @front."],"tags":["ruby","index-error","data-structures","queue","empty-state","linked-list"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}