{"record":{"id":"9ddc6e6fd44d1d33","repo":"krahets/hello-algo","slug":"error-9ddc6e","errorCode":null,"errorMessage":"堆疊為空","messagePattern":"堆疊為空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"zh-hant/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/zh-hant/codes/ruby/chapter_stack_and_queue/array_stack.rb#L13-L49","documentation":"Raised by the pop method of the ArrayStack teaching class (backed by Ruby's Array) when is_empty? is true. Although Ruby's own Array.pop returns nil on empty, this teaching implementation explicitly raises IndexError to demonstrate proper stack-underflow handling. The guard fires before delegating to @stack.pop.","triggerScenarios":"Calling stack.pop on a newly constructed stack, calling pop more times than elements were pushed, or popping in a drain loop without an emptiness check.","commonSituations":"Assuming the stack has elements when it does not; mismatched push/pop counts; treating this stack like a raw Ruby Array (which silently returns nil on empty pop).","solutions":["Check stack.is_empty? before calling pop.","Use while !stack.is_empty? to drain the stack safely.","Return nil when empty: stack.is_empty? ? nil : stack.pop.","Be aware this is stricter than Ruby's native Array.pop — do not assume nil-return semantics."],"exampleFix":"# before\n3.times { val = stack.pop }  # raises if stack has fewer than 3 elements\n\n# after\nuntil stack.is_empty?\n  val = stack.pop\nend","handlingStrategy":"validation","validationCode":"return nil if stack.is_empty?\nstack.pop","typeGuard":"# Ruby: safe pop\ndef safe_pop(stack)\n  stack.is_empty? ? nil : stack.pop\nend","tryCatchPattern":"begin\n  val = stack.pop\nrescue IndexError\n  val = nil  # stack underflow\nend","preventionTips":["Do not assume nil-return semantics like Ruby's native Array.pop — this raises.","Use 'until stack.is_empty?' to drain.","Track push/pop counts to catch underflow early."],"tags":["ruby","index-error","data-structures","stack","empty-state","stack-underflow"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}