From: "David A. Black" Date: 2005-08-08T10:45:28+09:00 Subject: Re: Adding yet another Array.new form Hi -- On Mon, 8 Aug 2005, Kirk Haines wrote: > On Sunday 07 August 2005 10:50 am, David A. Black wrote: > >>>> def a >>>> returning ary = [] do >>>> ... construct ary by adding elements to it ... >>>> end >>>> end >> >> [...] >> >>> I'd rather vote in favor of including #returning to the Ruby core. >>> It is a very helpful method to DRY. >> >> It feels a bit side-effect-dependent-ish, as written. It might be >> nicer with a more traditional yield/block param syntax: >> >> returning [] do |ary| ... end >> >> That shows more of the separation between the fact that you're >> returning an array, and the fact that you're assigning the name ary to >> that array for use inside the block. > > It should work either way. I haven't looked at the one in Rails, but mine: > > module Kernel > def returning(*vals) > yield *vals > end > end > > > def a > returning tmp = [] do > tmp << 1; tmp << 2; tmp << 3 > end > end That only works by coincidence: tmp << 3 happens to return tmp :-) If anything else is the last expression in your block, you'll get a different result: def a returning tmp = [] do tmp << 1; tmp << 2; tmp << 3 puts "I've finished inserting into tmp!" end end a # => nil, because it returns the value of the puts statement #returning has to explicitly return the thing it yields; otherwise it will return whatever the block it yielded to returns. David -- David A. Black dblack@wobblini.net