4.15.2.1. Použití iterátoru
From: "Hal E. Fulton" hal9000@hypermetrics.comHere's a way to look at it.
ruby-talk(51035)
Do you find "each" useful? And other iterators?
Have you ever wanted to write an iterator for a class
of your own (that didn't inherit from a class already
having one)?
In a case like that, you would use yield.
Have you ever wanted to write (what I call) a "non-iterating
iterator" that does some housekeeping, calls a block, and
does more housekeeping? Then you would use yield.
Definitive examples of the non-iterating iterator:
File.open("file") { block } # open, do block, close
Mutex.synchronize { block } # grab, do block, release
Dir.chdir("dir") { block } # cd, do block, cd back
If you don't understand how this works, try this:
def do_something
puts "Before"
yield # Basically call the block
puts "After"
end
do_something { puts "I'm doing something" }
Output:
Before
I'm doing something
After
Secondly, note that if you want an "iterating" iterator, you
would do a yield inside a loop. Control is traded back and
forth between the iterator and its block.
Thirdly, note that yield returns a value (which is the last
expression evaluated inside the block). This is useful for
things like Enumerable#select and others.