On Mon, 13 Feb 2006, the_crazy88 wrote:
Result is 7
But the equivalent ruby code doesn’t work:
That’s because it’s not equivalent
NoMethodError: undefined method
b' for main:Object from (irb):40:inx’
It shouldn’t; it should complain that you’ve called a with no
arguments instead of two.
When you do this:
Ruby evaluates the expression ‘a’, and that’s a method call – so it
tries to call the method a, but that method takes two arguments and
you haven’t provided any.
You can pass method names around, as strings or symbols, and then
“send” the method name to an object (or self, by default):
x + y
puts x(:a) # 7
There are also some more elaborate mechanisms involving Method
objects, but the above might achieve what you need.
David A. Black (firstname.lastname@example.org)
Ruby Power and Light (http://www.rubypowerandlight.com)
“Ruby for Rails” chapters now available
from Manning Early Access Program! http://www.manning.com/books/black