{"record":{"id":"1e6d7892255b0f89","repo":"krahets/hello-algo","slug":"error-1e6d78","errorCode":null,"errorMessage":"栈为空","messagePattern":"栈为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/ruby/chapter_stack_and_queue/array_stack.rb","lineNumber":31,"sourceCode":"\n  ### 获取栈的长度 ###\n  def size\n    @stack.length\n  end\n\n  ### 判断栈是否为空 ###\n  def is_empty?\n    @stack.empty?\n  end\n\n  ### 入栈 ###\n  def push(item)\n    @stack << item\n  end\n\n  ### 出栈 ###\n  def pop\n    raise IndexError, '栈为空' if is_empty?\n\n    @stack.pop\n  end\n\n  ### 访问栈顶元素 ###\n  def peek\n    raise IndexError, '栈为空' if is_empty?\n\n    @stack.last\n  end\n\n  ### 返回列表用于打印 ###\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/codes/ruby/chapter_stack_and_queue/array_stack.rb#L13-L49","documentation":"Raised by `ArrayStack#pop` (array_stack.rb:31) when `is_empty?` is true. The stack delegates storage to Ruby's `Array#pop`; the guard exists to throw a descriptive IndexError rather than letting `Array#pop` silently return nil. It enforces the stack ADT contract that pop on an empty container is an error.","triggerScenarios":"Calling `stack.pop` when the backing `@stack` array is empty. Occurs after popping all pushed items, or on a freshly constructed stack.","commonSituations":"Unbalanced push/pop pairs (more pops than pushes); expression-evaluation or backtracking algorithms that over-pop; test calling pop before any push.","solutions":["Check `stack.is_empty?` before calling `pop`.","Track push/pop balance with a counter in the caller.","Rescue IndexError if an empty pop is a recoverable condition."],"exampleFix":"# before\nval = stack.pop\n\n# after\nval = stack.is_empty? ? nil : stack.pop","handlingStrategy":"validation","validationCode":"return nil if stack.is_empty?\nstack.pop","typeGuard":"def stack_popable?(stack)\n  stack.respond_to?(:is_empty?) && stack.respond_to?(:pop) && !stack.is_empty?\nend","tryCatchPattern":"begin\n  stack.pop\nrescue IndexError\n  nil\nend","preventionTips":["Check is_empty? before pop.","Maintain a push/pop balance invariant in the caller.","In backtracking, verify depth > 0 before popping."],"tags":["ruby","stack","precondition","empty-state"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}