if baz > 10
func = :foo
else
func = :bar
end
result = self.send(func) if baz > 10
func = method(:foo)
else
func = method(:bar)
end
result = func.call
Here, we actually deal with the Method objects, rather than just sending a dynamic message. Although the send() approach would be closer to idiomatic Ruby, I wanted to emphasize that dealing with methods as first class objects in Ruby is indeed possible.It's fun to contrast this with Lua, by the way.
a = lambda { |x| x + 1 }
a(3) #=> 4
But since it doesn't, the alternatives are not too bad (though likely far too numerous for Python tastes) a[3] #=> 4
a.(3) #=> 4 (on Ruby 1.9)
I think that Ruby's ability to call methods without () make for better readability in the case of writing domain specific interfaces, but come at a cost in other places. Personally I think it's a worthwhile tradeoff but I can see the other side of the argument. p = Proc.new {|str| puts "Hello #{str}" }
p["World"] # prints "Hello World"
:)