some_string = "i love lamp"
another_string = "i love desk"
def some_string.lovehate
if match /love/
sub /love/, "hate"
elsif match /hate/
sub /hate/, "love"
end
end
puts some_string.lovehate # => "i hate lamp"
puts another_string.respond_to? :lovehate # => false
m = some_string.method(:lovehate).unbind
m.bind(another_string).call # fails
失败了
singleton method called for a different object (TypeError)
很明显,出于某种原因,Ruby 程序员认为这是一个坏主意。我的问题是是什么阻止我这样做?
最佳答案
这与 UnboundMethods 通常的工作方式一致。您将它们绑定(bind)到的对象必须是 kind_of?该方法来自的类。 another_string
不是 some_string
的单例类的后代(就像没有其他对象一样),因此您无法绑定(bind) some_string
的方法> 的单例类。
关于ruby - 为什么我不能将单例方法附加到另一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213796/