From: David Alan Black Date: 2001-02-11T20:26:14+09:00 Subject: [ruby-talk:10706] Re: Passing on a block to a called method On Sun, 11 Feb 2001, Michael Schuerig wrote: > David Alan Black wrote: > > > On Sun, 11 Feb 2001, Michael Schuerig wrote: > > > > def openAsText(file) > > > block = Proc.new > > > > > > filter = buildTextFilter(file) > > > > > > if filter.empty? > > > File.open(file) { |f| block.call(f) } > > > else > > > IO.popen("cat #{file} #{filter}") { |f| block.call(f) } > > > end > > > end > > > Your example looks like it might also lend itself to a nice 'yield' > > approach: > > > > if filter.empty? > > yield File.open(file) > > else > > yield IO.popen("cat....") > > end > > > > in which case openAsText wouldn't have to know about the block at > > all. (I can't help it -- I love 'yield'!) > > That's what I've been looking for. Thanks! Maybe I'll learn to love > 'yield', too. At least I'm one step further after understanding why and > how the above works. I should add that, if you're definitely only deriving one value per method call, then it probably makes more sense to have it be the method's return value (instead of yielding it). You could also test for "block_given?", and decide whether to yield a value, or just return it, on that basis. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav