【发布时间】:2016-02-15 22:48:03
【问题描述】:
Method#unbind 返回一个对方法的UnboundMethod 引用,以后可以使用UnboundMethod#bind 将其绑定到另一个对象。
class Foo
attr_reader :baz
def initialize(baz)
@baz = baz
end
end
class Bar
def initialize(baz)
@baz = baz
end
end
f = Foo.new(:test1)
g = Foo.new(:test2)
h = Bar.new(:test3)
f.method(:baz).unbind.bind(g).call # => :test2
f.method(:baz).unbind.bind(h).call # => TypeError: bind argument must be an instance of Foo
最初,我认为这非常棒,因为我预计它的工作方式类似于 JavaScript 的 Function.prototype.call()/Function.prototype.apply()。但是,您要将方法绑定到的对象必须属于同一类。
我能想到的唯一应用是如果你取消绑定一个方法,失去原来的实现(在原来的或单例类中重新定义方法)然后重新绑定并调用它。
【问题讨论】:
-
我在这里找到了一个简洁的解释 - blog.jayfields.com/2006/12/ruby-alias-method-alternative.html
-
@WandMaker,好主意。它属于我描述的类别。如果这是它存在的唯一原因,我会感到惊讶。
标签: ruby methods metaprogramming