On Mon, Jun 30, 2014 at 5:58 PM, Addis Aden <addis.aden / gmail.com> wrote:
> Hiii,
>
> i am new to this ruby-talk list, so i hope my question is not annoying
> (especially for my not so goood english).
>
> My question is simple. Is there a way to store a method in a variable? I
> know that every method can be called with the keyword and send, but is there
> a way to make it direct callable?
>
> As example:
>
> def addition(a, b)
>     a + b
> end
>
> x = addition
> x(2, 3) # => 5
>
> Is there a method like partial or anything like this in ruby?
>

2.0.0p195 :001 > def addition(a, b)
2.0.0p195 :002?>       a + b
2.0.0p195 :003?>   end
2.0.0p195 :006 > x = method(:addition)
 => #<Method: Object#addition>
2.0.0p195 :010 > x.call 2, 3
 => 5

The standalone method is still bound to the object:

2.0.0p195 :011 > class A
2.0.0p195 :012?>   def initialize a
2.0.0p195 :013?>     @a = a
2.0.0p195 :014?>     end
2.0.0p195 :015?>   def addition y
2.0.0p195 :016?>     @a + y
2.0.0p195 :017?>     end
2.0.0p195 :018?>   end
 => nil
2.0.0p195 :019 > a = A.new 3
 => #<A:0x000000026024b0 @a=3>
2.0.0p195 :022 > x = a.method :addition
 => #<Method: A#addition>
2.0.0p195 :023 > x.call 4
 => 7

You can also get an unbound method, but you can only call it after
binding it to an object of the same class (kind_of):

2.0.0p195 :026 > u = x.unbind
 => #<UnboundMethod: A#addition>
2.0.0p195 :027 > u.call 4
NoMethodError: undefined method `call' for #<UnboundMethod: A#addition>

2.0.0p195 :028 > b = u.bind(A.new 12)
 => #<Method: A#addition>
2.0.0p195 :029 > b.call 4
 => 16

Hope this helps,

Jesus.