我正在学习我的对象个性化,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
对象上的单例方法并在usingfoo
中执行该方法?talk
class Foo
foo.talk
在调用中寻找输出foo.talk
为"huanng"
.
编辑:
根据@Anthony Alberto的建议,我可以访问talk
of 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
在同一条路线上,如何绕过单例talk
方法和?Foo
talk
talk
Bar
编辑
最后不是答案,但接近实际需要的是@Neil
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:0x1200db0>>
foo.dup.talk
#"huanng"
#=> "huanng"
foo.talk
#"hukkangg"
#=> "hukkangg"