Louis J Scoras
11/14/2006 2:38:00 PM
On 11/13/06, S. Robert James <srobertjames@gmail.com> wrote:
> I still maintain that this is clever code. Every new (pseudo)keyword
> comes at a cost, of having to learn (and keep in your head) something
> new. They have to justify their cost by truly cleaning up the code -
> and I haven't seen an example of that yet.
It's not a new keyword though, it's simply a method and a very useful
one at that. In my opinion, the intention comes off pretty clearly,
and if not there is always the documentation.
Consider how many times you see the idiom:
def foo
o = Object.new
o.mutate!
o
end
The fact that you see that so much is just crying out for an
additional abstraction, and that's what 'returning' provides.
In fact, something like this could be helpful in other scenarios as
well. Take Enumerable#inject for example. Many times you are just
making changes to the state parameter and returning that at the end of
the block. Try something like this:
module Enumerable
def injecting(s)
inject(s) do |k, i|
yield(k, i); k
end
end
end
Say you want to count letters--
some_text.inject(Hash.new(0)) {|h,l| h[l] +=1; h}
vs
some_text.injecting(Hash.new(0) {|h,l| h[l] += 1}
It's not about being clever, or saving some typing (as this example
shows, its the same about of characters). It's about abstracting away
repeated patterns; that's almost always a win in my book.
--
Lou.