class UnboundMethod

Ruby 支持两种形式的对象化方法。Class Method 用于表示与特定对象关联的方法:这些方法对象绑定到该对象。可以使用 Object#method 为对象创建绑定的方法对象。

Ruby 还支持未绑定的方法;即不与特定对象关联的方法对象。可以通过调用 Module#instance_method 或在绑定的方法对象上调用 unbind 来创建这些方法对象。这两种方法的结果都是一个 UnboundMethod 对象。

未绑定的方法只有在绑定到对象后才能调用。该对象必须是方法原始类的 kind_of?。

class Square
  def area
    @side * @side
  end
  def initialize(side)
    @side = side
  end
end

area_un = Square.instance_method(:area)

s = Square.new(12)
area = area_un.bind(s)
area.call   #=> 144

未绑定的方法是对其对象化时的方法的引用:随后对底层类的更改不会影响未绑定的方法。

class Test
  def test
    :original
  end
end
um = Test.instance_method(:test)
class Test
  def test
    :modified
  end
end
t = Test.new
t.test            #=> :modified
um.bind(t).call   #=> :original