Re:Object#returning (Ruby's K Combinator)
by raganwald on Thursday August 28, 2008 @11:16AM
(#289187)
Here's a use for the K Combinator that isn't Your Father's Imperative Programming. I sometimes want an arbitrary, one-off object when testing or prototyping things, perhaps in irb:
[ Parent
| on HN ]
Re:Object#returning (Ruby's K Combinator)
by zenspider on Thursday August 28, 2008 @07:03PM
(#289576)
foo = returning(Object.new) do |f|
def f.bar
...
end
def f.bash
...
end
end
# vs
foo = Object.new
def foo.bar
...
end
def foo.bash
...
end
1 line shorter, less indentation, more clear. What does returning get you besides another message send and block activation? I have yet to see a good use for it. (yes, I'm biased. calibrate accordingly)
Re:Object#returning (Ruby's K Combinator)
by raganwald on Thursday August 28, 2008 @08:52PM
(#289658)
It really depends. If the definitions of foo.bar and foo.bash make sense independantly of the assignment to foo, I prefer the second form as well. If in my brain the whole thing is "atomic", I prefer the returning form or to make a helper method so that they are composed into a logical chunk.
For the same reason, I write:
foo = bar
bash = blitz
When teh two statements are independant, and: foo, bar = bash, blitz
When they are deeply related and should not be broken up. Sometimes that is hard to read and I will get gratuitous: begin
foo = bar
bash = blitz
end
What can I say... that uses more characters than needed. It isn't always about saving electrons for me.