{"record":{"id":"ae1e7945e281def4","repo":"krahets/hello-algo","slug":"error-ae1e79","errorCode":null,"errorMessage":"队列为空","messagePattern":"队列为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/ruby/chapter_stack_and_queue/array_queue.rb","lineNumber":52,"sourceCode":"    # 通过取余操作实现 rear 越过数组尾部后回到头部\n    rear = (@front + size) % capacity\n    # 将 num 添加至队尾\n    @nums[rear] = num\n    @size += 1\n  end\n\n  ### 出队 ###\n  def pop\n    num = peek\n    # 队首指针向后移动一位，若越过尾部，则返回到数组头部\n    @front = (@front + 1) % capacity\n    @size -= 1\n    num\n  end\n\n  ### 访问队首元素 ###\n  def peek\n    raise IndexError, '队列为空' if is_empty?\n\n    @nums[@front]\n  end\n\n  ### 返回列表用于打印 ###\n  def to_array\n    res = Array.new(size, 0)\n    j = @front\n\n    for i in 0...size\n      res[i] = @nums[j % capacity]\n      j += 1\n    end\n\n    res\n  end\nend\n","sourceCodeStart":34,"sourceCodeEnd":70,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/ruby/chapter_stack_and_queue/array_queue.rb#L34-L70","documentation":"Raised by `ArrayQueue#peek` (array_queue.rb:52) when `is_empty?` is true. `peek` returns `@nums[@front]` to expose the head without dequeueing; on an empty queue `@front` points at a stale slot and the read is meaningless. The `pop` method delegates to `peek`, so an empty dequeue also surfaces here.","triggerScenarios":"Calling `queue.peek` or `queue.pop` when `@size == 0`. Occurs after consuming all elements, or before the first enqueue.","commonSituations":"Consumer loop that pops until empty then peeks once more; queue drained by another part of the code; test running peek before any push.","solutions":["Guard with `unless queue.is_empty?` before `peek` or `pop`.","Drive the consume loop with `while queue.size > 0`.","Rescue IndexError at the call site if empty is a normal sentinel."],"exampleFix":"# before\nhead = queue.peek\n\n# after\nhead = queue.is_empty? ? nil : queue.peek","handlingStrategy":"validation","validationCode":"return nil if queue.is_empty?\nqueue.peek","typeGuard":"def queue_readable?(queue)\n  queue.respond_to?(:is_empty?) && queue.respond_to?(:peek) && !queue.is_empty?\nend","tryCatchPattern":"begin\n  queue.peek\nrescue IndexError\n  nil\nend","preventionTips":["Check is_empty? before peek or pop.","Use while queue.size > 0 as the consumer loop condition.","Do not assume the queue is non-empty after an async drain."],"tags":["ruby","queue","precondition","empty-state"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}