{"record":{"id":"24a9c7dc234af232","repo":"krahets/hello-algo","slug":"stack-is-empty-24a9c7","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/array_stack.rb","lineNumber":31,"sourceCode":"\n  ### Get stack length ###\n  def size\n    @stack.length\n  end\n\n  ### Check if stack is empty ###\n  def is_empty?\n    @stack.empty?\n  end\n\n  ### Push ###\n  def push(item)\n    @stack << item\n  end\n\n  ### Pop ###\n  def pop\n    raise IndexError, 'Stack is empty' if is_empty?\n\n    @stack.pop\n  end\n\n  ### Access top element ###\n  def peek\n    raise IndexError, 'Stack is empty' if is_empty?\n\n    @stack.last\n  end\n\n  ### Return list for printing ###\n  def to_array\n    @stack\n  end\nend\n\n### Driver Code ###","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/en/codes/ruby/chapter_stack_and_queue/array_stack.rb#L13-L49","documentation":"Raised by ArrayStack#pop (en/codes/ruby/chapter_stack_and_queue/array_stack.rb:31) when the underlying @stack array is empty. ArrayStack wraps a Ruby Array; it re-implements the empty guard because the teaching version wants an explicit IndexError with its own message rather than the stdlib nil-return from Array#pop.","triggerScenarios":"Calling stack.pop when stack.is_empty? is true — i.e. when @stack has no elements. Occurs after popping as many items as were pushed, or on a brand-new ArrayStack before any push.","commonSituations":"Unbalanced push/pop counts in a bracket-matching or expression-evaluation exercise; popping in a while loop with is_empty? checked against the wrong variable; reusing a stack across recursive calls that fully drain it.","solutions":["Check stack.is_empty? (or stack.size == 0) before calling pop.","Ensure every pop in a loop has a matching earlier push; verify counts are balanced.","Catch IndexError around the pop and return a default (nil or sentinel) when empty is an expected state."],"exampleFix":"# before\nwhile true\n  stack.pop # raises once drained\nend\n\n# after\nstack.pop until stack.is_empty?","handlingStrategy":"validation","validationCode":"stack.pop unless stack.is_empty?","typeGuard":"def stack_nonempty?(s); s.respond_to?(:is_empty?) && !s.is_empty?; end","tryCatchPattern":"begin\n  stack.pop\nrescue IndexError\n  nil # empty stack\nend","preventionTips":["Check is_empty? before every pop.","Keep push/pop counts balanced in matching/parsing algorithms.","Push a sentinel frame if your algorithm assumes a non-empty top."],"tags":["ruby","stack","array","precondition","indexerror"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}