单例方法是否可以在Ruby中调用绕过?

时间:2013-03-14 13:58:12

标签: ruby

我在IRB中学习了个性化的对象,我确实尝试了下面的代码:

class Foo
    def talk
        p "huanng"
    end
end
#=> nil

module Bar
    def talk
        p "hunnggg"
    end
end
#=> nil

foo = Foo.new
#=> #<Foo:0x1152b88>

class << foo
    def talk
        p "hukkangg"
    end
 include Bar
end
#=> #<Class:#<Foo:0x1152b88>>

foo.talk
"hukkangg"
#=> "hukkangg"

以上输出非常明显。

无论如何通过调用对象talk上的单例方法foo并使用talkclass Foo内执行方法foo.talk? / p>

将来电foo.talk的输出视为"huanng"

修改

根据 @Anthony Alberto 的建议,我可以访问talk的{​​{1}}。

Bar

在同一条路线上,如何绕过class Foo def talk p "huanng" end end #=> nil module Bar def talk p "hunnggg" end end #=> nil foo = Foo.new #=> #<Foo:0x1152b88> class << foo def talk super return p "hukkangg" end include Bar end #=> #<Class:#<Foo:0x11f6670>> foo.talk "hunnggg" #=> nil 的{​​{1}}绕过talk的单身方法Footalk

修改

最后不是答案,但接近实际需要的是 @Neil

talk

2 个答案:

答案 0 :(得分:2)

技术上不会针对同一个实例进行调用,但dup不会复制单例内容(clone ),所以你可以这样做:

foo.dup.talk

。 。 。在某些情况下它可能已经足够好了吗?

答案 1 :(得分:2)

你可以,虽然它(理解上)令人费解。你从类中获取实例方法(绕过单例类)并在foo上调用它:

an_unbound_method = foo.class.instance_method(:talk)
a_bound_method = an_unbound_method.bind(foo)
a_bound_method.call
相关问题