) An UnboundMethod must be
bound to a class before it can be invoked.
Method
Method objects are UnboundMethods that have been bound to an object with
UnboundMethod#bind. Alternatively, they can be obtained with Object#method.
Let??™s examine some ways to get Proc and Method objects. We??™ll use the Fixnum#+
method as an example. We usually invoke it using the dyadic syntax:
3 + 5 # => 8
However, it can be invoked as an instance method of a Fixnum object, like any other
instance method:
3.+(5) # => 8
We can use the Object#method method to get an object representing this instance
method. The method will be bound to the object that method was called on, 3.
add_3 = 3.method(:+)
add_3 # => #
This method can be converted to a Proc, or called directly with arguments:
Ruby Foundations | 21
add_3.to_proc # => #
add_3.call(5) # => 8
# Method#[] is a handy synonym for Method#call.
add_3[5] # => 8
There are two ways to obtain an unbound method. We can call instance_method on
the class object:
add_unbound = Fixnum.instance_method(:+)
add_unbound # => #
We can also unbind a method that has already been bound to an object:
add_unbound == 3.method(:+).unbind # => true
add_unbound.bind(3).call(5) # => 8
We can bind the UnboundMethod to any other object of the same class:
add_unbound.bind(15)[4] # => 19
However, the object we bind to must be an instance of the same class, or else we get
a TypeError:
add_unbound.
Pages:
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47