{"record":{"id":"9e9819812e7f6506","repo":"krahets/hello-algo","slug":"error-9e9819","errorCode":null,"errorMessage":"堆疊為空","messagePattern":"堆疊為空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb","lineNumber":41,"sourceCode":"  ### 入堆疊 ###\n  def push(val)\n    node = ListNode.new(val)\n    node.next = @peek\n    @peek = node\n    @size += 1\n  end\n\n  ### 出堆疊 ###\n  def pop\n    num = peek\n    @peek = @peek.next\n    @size -= 1\n    num\n  end\n\n  ### 訪問堆疊頂元素 ###\n  def peek\n    raise IndexError, '堆疊為空' if is_empty?\n\n    @peek.val\n  end\n\n  ### 將鏈結串列轉化為 Array 並反回 ###\n  def to_array\n    arr = []\n    node = @peek\n    while node\n      arr << node.val\n      node = node.next\n    end\n    arr.reverse\n  end\nend\n\n### Driver Code ###\nif __FILE__ == $0","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb#L23-L59","documentation":"Raised by the peek method of the LinkedListStack teaching class (a singly-linked-list LIFO stack) when is_empty? is true. It guards @peek.val (the top node pointer) so you never dereference nil. Note that pop calls peek internally, so popping an empty stack also propagates this error.","triggerScenarios":"Calling stack.peek or stack.pop on a newly constructed stack, calling them after all elements were popped, or draining past empty in a loop.","commonSituations":"Peeking/popping before pushing; mismatched push/pop counts; assuming the stack has elements when it does not.","solutions":["Check stack.is_empty? before calling peek or pop.","Return nil when empty: stack.is_empty? ? nil : stack.peek.","Use until stack.is_empty? for safe draining.","Ensure at least one push precedes any peek or pop."],"exampleFix":"# before\ntop = stack.peek  # raises on empty stack\n\n# after\ntop = stack.is_empty? ? nil : stack.peek","handlingStrategy":"validation","validationCode":"return nil if stack.is_empty?\nstack.peek","typeGuard":"# Ruby: safe peek\ndef safe_peek(stack)\n  stack.is_empty? ? nil : stack.peek\nend","tryCatchPattern":"begin\n  top = stack.peek\nrescue IndexError\n  top = nil\nend","preventionTips":["Check is_empty? before peek or pop (pop calls peek internally).","Ensure at least one push precedes any peek.","This prevents a nil.val NoMethodError on @peek node."],"tags":["ruby","index-error","data-structures","stack","empty-state","linked-list","stack-underflow"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}