From: "Hal E. Fulton" Date: 2002-09-23T22:09:43+09:00 Subject: Re: Teach me about yield ----- Original Message ----- From: "Joseph Benik" Newsgroups: comp.lang.ruby To: "ruby-talk ML" Sent: Monday, September 23, 2002 7:15 AM Subject: Teach me about yield > i've programmed computers for the greater portion of my life and find > myself really "set in my ways" when it comes to solving problems. i > have both Dave and Matz's ruby books and have read the description of > yield numerous times, yet never used a single yield statement in just > over a year of ruby coding. > > when do you use yield? has it solved problems for you when you > couldn't find another solution? how did you first start using yield? Here's a way to look at it. 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. > i want to expand my mind and wrap it around this concept, any pointers > (besides RTFM), or sample code would be greatly appreciated There's nothing wrong with RTFM (Ruby Training From Matz). :) HTH, Hal