Project

General

Profile

Actions

Bug #20223

closed

For simple objects each_cons appears to work as I expect, but for other objects it seems to fail to terminate iterations when I would expect.

Added by mjflynt (Jeffrey Flynt) 5 months ago. Updated 5 months ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [aarch64-linux]
[ruby-core:116483]

Description

Reproduce process:

p `ruby -v`
class X
include Enumerable
  attr_accessor :obj
  def initialize = @obj = (1..5).to_a
  def each(&block) = yield @obj.each(&block)
end

wtf = X.new

(1..5).each_cons(3) { |g| p g }
p '~' * 20
(1..5).to_a.each_cons(3) { |g| p g }
p '~' * 20
('a'..'e').each_cons(3) { |g| p g }
p '~' * 20

wtf.each_cons(3) { |g| p g }

Result of reproduce process

"ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [aarch64-linux]\n"
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
"~~~~~~~~~~~~~~~~~~~~"
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
"~~~~~~~~~~~~~~~~~~~~"
["a", "b", "c"]
["b", "c", "d"]
["c", "d", "e"]
"~~~~~~~~~~~~~~~~~~~~"
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, [1, 2, 3, 4, 5]]

[Done] exited with code=0 in 0.173 seconds

Expected result and the reason why you expect

I expect the results to not include the last line of output "[4, 5, [1, 2, 3, 4, 5]]" because my understanding is each_cons ends its iteration over the collection before it runs out of elements. In this case, this fourth row does not have enough elements to do three consecutive elements, but it is doing so anyway, appearing to use the original array as the third element before it completes.

Updated by jeremyevans0 (Jeremy Evans) 5 months ago

  • Status changed from Open to Rejected

Not a bug, you are doing yield @obj.each(&block), and Array#each returns the receiver.

Actions

Also available in: Atom PDF

Like0
Like1