我在我的IRB中玩singleton class
。這樣做嘗試了以下片段。`singleton`方法在Ruby中駐留在哪裏?
class Foo ; end
#=> nil
foo = Foo.new
#=> #<Foo:0x2022738>
foo.define_singleton_method(:bar , method(:puts))
#=> #<Method: Object(Kernel)#puts>
這裏上面我剛剛創建的Foo
類的實例singleton
方法。
foo.bar("hi")
hi
#=> nil
foo.singleton_methods
#=> [:bar]
foo_sing = foo.singleton_class
#=> #<Class:#<Foo:0x2022738
foo_sing.is_a? Class
#=> true
foo_sing.instance_of? Class
#=> true
foo_sing.inspect
#=> "#<Class:#<Foo:0x1e06dc8>>"
在上面我試圖在Foo
類的實例創建singleton class
。並且還測試foo_sing
對類Foo
的實例是否參照singleton class
。
foo_sing.methods(false)
#=> []
foo_sing.methods.include? :bar
#=> false
在上面我一直在尋找,如果singleton_method
bar
是在foo_sing
或not.But發現它不存在there.Then我的問題是 - 哪裏那些singleton_method
居住在紅寶石?
foo_sing.new.methods(false)
#TypeError: can't create instance of singleton class
# from (irb):10:in `new'
# from (irb):10
# from C:/Ruby193/bin/irb:12:in `<main>'
class Bas < foo_sing ; end
#TypeError: can't make subclass of singleton class
# from (irb):16
# from C:/Ruby193/bin/irb:12:in `<main>'
在我被檢查,如果我們能夠創造的singleton class
實例或不與子類的singleton class
,像普通類以上的部分。但是我發現的答案是否定的。 它背後的概念或理論或目的是什麼?
再次在下面的代碼中,我可以看到在singleton class
內部重寫了相同的名稱方法。但是當我在上面問的時候沒有找到類中的那個方法時。
class Foo ; end
#=> nil
foo = Foo.new
#=> #<Foo:0x225e3a0>
def foo.show ; puts "hi" ; end
#=> nil
foo.show
#hi
#=> nil
class << foo ;def show ; puts "hello" ; end ;end
#=> nil
foo.show
#hello
#=> nil
爲什麼他們住在哪裏很重要?他們工作起來不是更重要嗎?如果對你來說真的很重要,請查看源代碼。 – 2013-03-16 16:32:39
我認爲@iAmRubuuu想要了解單身人士課程。 – 2013-03-16 16:34:54
順便說一句,我會在幾天後發佈一篇博文,並會嘗試回答這些問題。 – 2013-03-16 16:35:44