Well, unless I'm missing something, the method with yield
simply doesn't work. Try it:
e = Enumerator.new do |y|
y << 1
y << 2
y << 3
end
f = Enumerator.new do
yield 1
yield 2
yield 3
end
e.each { |x| puts x }
f.each { |x| puts x }
Which produces this:
telemachus ~ $ ruby yield.rb
1
2
3
yield.rb:13:in `block in <main>': no block given (yield) (LocalJumpError)
from yield.rb:19:in `each'
from yield.rb:19:in `each'
from yield.rb:19:in `<main>
When he says (page 304) "you don't do this," he doesn't mean "it's not the best way to do it." He means, "that won't work."
Edit: You can, however, call yield explicitly this way:
e = Enumerator.new do |y|
y.yield 1
y.yield 2
y.yield 3
end
If you find saying yield
more explicit or clearer than <<
, then do it that way.
Second edit: Looking at David's original post and Jorg's updated answer, I think that there was a confusion originally about the question. Jorg thought David was asking about the difference between Enumerator::Yielder#yield
and Enumerator::Yielder::<<
, but David wasn't sure what The Well Grounded Rubyist means when it says "don't write yield 1
etc." My answer applies to the question about The Well Grounded Rubyist. (When I looked this thread back over today, my answer looked odd in the light of other updates.)