Feature #5389

New method Enumerator#iterate

Added by Joey Zhou about 4 years ago. Updated about 3 years ago.

Assignee:Yukihiro Matsumoto


If we want to iterate over the elements of a enumerable object with multiple blocks, we can use the Enumerator class.

A method 'iterate' is required, we can write it in Ruby:

class Enumerator
  def iterate
    yield_value = self.next
    return_value = yield yield_value
    self.feed return_value

Well, here is an example:

array = (1..10).to_a
enum = array.map!

loop do
  enum.iterate {|n| n + 10 }
  enum.iterate {|n| n * 2 }
  enum.iterate {|n| -n }

p array # => [11, 4, -3, 14, 10, -6, 17, 16, -9, 20]

We want to map an array: the 1st element use blk1, the 2nd use blk2, the 3rd use blk3...

I think this Enumerator#iterate method is sometimes useful, so would you please introduce it into the language core?


#1 Updated by Yui NARUSE about 4 years ago

Enumerator#next is not enough?

#2 Updated by Joey Zhou about 4 years ago

Yui NARUSE wrote:

Enumerator#next is not enough?

array = (1..10).to_a
enum = array.map!

loop do
enum.next {|n| n + 10 }
enum.next {|n| n * 2 }
enum.next {|n| -n }

p array # => [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

#next needs no blocks. #iterate is a combination of #next and #feed, I think it's useful for External Iterators.

#3 Updated by Yusuke Endoh over 3 years ago

  • Status changed from Open to Assigned
  • Assignee set to Yukihiro Matsumoto

#4 Updated by Yusuke Endoh about 3 years ago

  • Target version set to next minor

Also available in: Atom PDF