ruby - 为什么我不能将单例方法附加到另一个对象?

标签 ruby oop singleton singleton-methods

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/

相关文章:

ruby-on-rails - JBuilder as_json to_json

php - 是否有可能将过程代码转换为 PHP 中的面向对象代码?

java - Glassfish 初始化 Singleton bean 两次

ruby - 我如何模拟在 rspec 中创建目录?

rspec 上的 Ruby 段错误

python - Python中的空类对象

javascript - 使用私有(private)变量创建单例的方法?

iphone - 同一单例类的方法名称部分?

java - Ruby 性能优于 Java 的案例

javascript - JS : TypeError: this. _init 不是函数。 (在 'this._init()' 中, 'this._init' 未定义)