[Ruby] conditional execution of block / method?
Bastiaan
ruby at redwebs.nl
Fri Jun 8 06:47:08 PDT 2007
Hi Folks,
This is my first post to this list, and it's not going make me
popular, I guess..
I have been coding Ruby for a little while now, and I find myself
doing this sometimes:
if(foo=bar.something)
foo.something_else
end
Obviously I only want to call #something_else on the output of
#something if #something is true and settle for nil/false otherwise.
I find this approach tedious. Maybe you people have a nice way around
this. My noob-approach woud be:
bar.something.if_so.something_else
and have that return nil or false if #something returned nil or false
itself. I'm aware that this potentially totally un-Rubyesque(?), but
you'd have to explicitly use the #if_so thingie if this behaviour is
wanted, so it's not really 'dangerous'. I'd also like to be able to
pass a block if #something's return evaluates to true.
I've come up with the (monstrous?):
# This allows you to only call a method or block on something that is
true.
class Object
# calls method or yields block if self
def if_so(method=nil, *args, &block)
if self
block_given? ? yield(self) : self.send(method.to_sym, args)
end
end
end
Any suggestion how this is done better, or any discussion that you
don't want/need this is appreciated.
Cheers, Bastiaan
More information about the Ruby
mailing list