Robert Klemme
1/29/2009 8:31:00 AM
2009/1/28 klochner <klochner@gmail.com>
>
> On Jan 28, 3:21 pm, Stefano Crocco <stefano.cro...@ali
> > Can you give an example of a situation where you think yield is used in place
> > of return? This way, we'll be able to understand better what you're referring
> > to and make more useful comments.
> >
> > Stefano
>
> The calling code would need to be modified to work with yield vs.
> return.
>
> Here's a slightly different example, because I see this a lot with
> multivariate return values:
>
> ##return style, with calling code below
> def returnfoo
> return foo1,foo2
> end
> a,b = returnfoo
> puts a; puts b
>
> vs.
>
> ##yield style, with calling code below
> def yieldfoo
> yield foo1, foo2
> end
> yieldfoo {|a,b| puts a; puts b }
>
>
> What I'm getting at is that I see ruby programmers use yield to
> essentially return values to the caller, the distinction being whether
> the block is executed by the caller or by the method (returnfoo/
> yieldfoo). It could be done either way because no operations are
> performed by the method after the yield.
IMHO that would be a bad use case for /yield/. The power of /yield/
comes from the fact that the method is in control _when_ and _how
often_ it invokes /yield/ and _what_ it passes on. Basically your
block is an anonymous callback function. For methods that simply do a
computation that does not need adjustment by custom code (the
callback) using /return/ is the most appropriate method.
Since with /yield/ the method is in control another typical idiom is
safe cleanup:
def x
yield 123
ensure
cleanup
end
File.open with block works that way.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end