{"record":{"id":"f2ba86ba57d193ba","repo":"krahets/hello-algo","slug":"error-f2ba86","errorCode":null,"errorMessage":"佇列為空","messagePattern":"佇列為空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"zh-hant/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/zh-hant/codes/ruby/chapter_stack_and_queue/array_queue.rb#L34-L70","documentation":"Raised by the peek method of the ArrayQueue teaching class when is_empty? is true. It prevents reading @nums[@front] when no elements are enqueued, which would return stale zero-initialized data. Note that pop also calls peek internally, so popping an empty queue propagates this error.","triggerScenarios":"Calling queue.peek or queue.pop on a newly constructed queue (size 0), calling them after all elements have been dequeued, or calling them in a drain loop that overshoots.","commonSituations":"Peeking or popping without checking emptiness; a consumer reading faster than the producer enqueues; using a fixed-count loop instead of a while !is_empty? loop to drain.","solutions":["Check queue.is_empty? before calling peek or pop.","Return nil or a sentinel for empty: queue.is_empty? ? nil : queue.peek.","Use while !queue.is_empty? for safe draining.","Track enqueue/dequeue counts to catch mismatches."],"exampleFix":"# before\nhead = queue.peek  # raises if queue is empty\n\n# after\nhead = queue.is_empty? ? nil : queue.peek","handlingStrategy":"validation","validationCode":"return nil if queue.is_empty?\nqueue.peek","typeGuard":"# Ruby: safe peek\ndef safe_peek(queue)\n  queue.is_empty? ? nil : queue.peek\nend","tryCatchPattern":"begin\n  head = queue.peek\nrescue IndexError\n  head = nil\nend","preventionTips":["Check is_empty? before peek or pop (pop calls peek internally).","Use 'while !queue.is_empty?' to drain safely.","Track enqueue/dequeue counts to detect consumer/producer mismatch."],"tags":["ruby","index-error","data-structures","queue","empty-state","circular-array"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}