From: Tim Hunter Date: 2004-12-04T09:52:40+09:00 Subject: Re: Using yield Joe Van Dyk wrote: > I come from a heavy C++ background, discovered Ruby a few months ago and > love it. > > I've found that using blocks is a very natural thing. However, I have not > once used 'yield'. I'm sure that there are events when using yield would > be helpful, but I have no clue when it would be appropriate to use. > > Thoughts? When do you use the 'yield' statement in code? > > Joe I use it with methods that create resources that need to be cleaned up after, the way File.open closes the file for you after the block terminates. If you're coming from C++, think destructors. Here's an example from RMagick. The Image#view method extracts a rectangle of pixels from an image and yields to a block (if present). Within the block you can address the pixels using [i][j] indexes. When the block ends, if any of the pixels have been modified all the pixels are stored ("sync'd") back to the image. The code looks like this: def view(x, y, width, height) view = View.new(self, x, y, width, height) if block_given? begin yield(view) ensure view.sync end return nil else return view end end You use #view like this: image.view(5, 10, 20, 20) do |view| view[5][7] = 'yellow' # other useful stuff... end