Tim Hunter
2/12/2006 9:46:00 PM
the_crazy88 wrote:
> 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:
>
> 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
>
In Ruby it's typical to encapsulate bits of code in Proc objects and
pass these objects around:
p = Proc.new {|x,y} x+y}
p.call(2,3) -> 5
If you're really wanting to pass methods around from one instance to
another, check out the doc for the UnboundMethod class with ri.