e.to_a
If you want to create an Array from your Enumerator, each element must first be extracted from it!
Ruby needs to make sure nothing is forgotten, and it needs to execute the entire block before returning the array. There may be another line that defines more elements:
e = Enumerator.new do |y| puts "Starting up the block!" (1..3).each {|i| y << i } puts "Exiting the block! (Not really)" (4..6).each {|i| y << i } puts "Exiting the block!" end
It outputs:
Starting up the block! Exiting the block! (Not really) Exiting the block! [1, 2, 3, 4, 5, 6]
Alternatives
Alternatively you can use:
e.next
p e.next p e.next p e.next p e.next
It outputs:
Starting up the block! 1 2 3 Exiting the block! enum.rb:11:in `next': iteration reached an end (StopIteration)
e.each
e.each do |x| puts x end
e.map
If you want to create an array, but see the correct execution order, you can use:
p e.map{ |x| px }
It outputs:
Starting up the block! 1 2 3 Exiting the block! [1, 2, 3]
source share