{"record":{"id":"543c554077f939b4","repo":"krahets/hello-algo","slug":"stack-is-empty-543c55","errorCode":null,"errorMessage":"Stack is empty","messagePattern":"Stack is empty","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"en/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb","lineNumber":41,"sourceCode":"  ### Push ###\n  def push(val)\n    node = ListNode.new(val)\n    node.next = @peek\n    @peek = node\n    @size += 1\n  end\n\n  ### Pop ###\n  def pop\n    num = peek\n    @peek = @peek.next\n    @size -= 1\n    num\n  end\n\n  ### Access top element ###\n  def peek\n    raise IndexError, 'Stack is empty' if is_empty?\n\n    @peek.val\n  end\n\n  ### Convert linked list to Array and return ###\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/en/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb#L23-L59","documentation":"Raised by LinkedListStack#peek (en/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb:41) when the stack is empty. peek returns @peek.val; @peek is nil at size == 0, so the guard prevents a nil dereference. pop calls peek first, so popping an empty linked-list stack also surfaces this message.","triggerScenarios":"Calling stack.peek or stack.pop when stack.size == 0 — before any push, or after the list has been fully unwound by pops.","commonSituations":"A recursive/backtracking stack drained by unwind; a delimiter/matching stack where the input closes more groups than it opened; peeking the top before the first push.","solutions":["Guard with stack.is_empty? before peek/pop.","Keep push and pop counts balanced; assert before unwinding.","Rescue IndexError and return a sentinel for the empty-top case."],"exampleFix":"# before\ntop = stack.peek # raises on empty\n\n# after\ntop = stack.is_empty? ? nil : stack.peek","handlingStrategy":"validation","validationCode":"stack.peek unless stack.is_empty?","typeGuard":"def stack_nonempty?(s); s.respond_to?(:is_empty?) && !s.is_empty?; end","tryCatchPattern":"begin\n  stack.peek\nrescue IndexError\n  nil\nend","preventionTips":["Guard peek/pop with is_empty?.","Maintain balanced push/pop in recursion/backtracking.","Push a sentinel for algorithms that peek unconditionally."],"tags":["ruby","stack","linked-list","precondition","indexerror"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}