Hi --
I've searched a bit about the subject, but I don't understand it. All I
want is to simply pass a function of one instance to another. In Python
this works, but in ruby not.
Python code would be:
def x(a,b):
return a+b
def y(a):
return a(3,4)
y(x)
# Result is 7
But the equivalent ruby code doesn't work:
That's because it's not equivalent
def a(x,y)
return x+y
end
def x(b)
return b(3,4)
end
x(a)
#Gives the following error in irb:
NoMethodError: undefined method `b' for main:Object
from (irb):40:in `x'
from (irb):42
from :0
It shouldn't; it should complain that you've called a with no
arguments instead of two.
When you do this:
x(a)
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):
def a(x,y)
x + y
end
def x(b)
send(b,3,4)
end
puts x(:a) # 7
There are also some more elaborate mechanisms involving Method
objects, but the above might achieve what you need.
David
···
On Mon, 13 Feb 2006, the_crazy88 wrote:
--
David A. Black (dblack@wobblini.net)
Ruby Power and Light (http://www.rubypowerandlight.com)
"Ruby for Rails" chapters now available
from Manning Early Access Program! Ruby for Rails