我是學對象的個性化在我IRB
,我曾嘗試下面的代碼:在Ruby中是否可以繞過singleton方法調用?
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"
以上輸出是如此的明顯。
反正通過傳遞該呼叫的對象foo
上的單身方法talk
並執行使用foo.talk
的class Foo
內的方法talk
?
尋找呼叫foo.talk
的輸出爲"huanng"
。
編輯:
按照建議從@Anthony阿爾貝託我能達到的Bar
talk
。
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
在同樣的路線如何達到Foo
talk
繞過單方法talk
和Bar
talk
?
編輯
最後沒有答案,但接近實際需要的是按照@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"
不確定的問題。您是否想通過查找並調用Foo的實例方法「talk」來調用它,或者想要找到一種方法來撤消對實例的更改(但僅限於您選擇的方法)? – 2013-03-14 14:05:58
當同樣的名字方法'talk'也在'foo'上定義爲單例方法時,查找調用'foo.talk'上的輸出爲'huanng'''。 – 2013-03-14 14:08:19
你是如何期待打電話給單身人士的方法? – 2013-03-14 14:10:12