2013-03-16 55 views
2

我在我的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_methodbar是在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 
+0

爲什麼他們住在哪裏很重要?他們工作起來不是更重要嗎?如果對你來說真的很重要,請查看源代碼。 – 2013-03-16 16:32:39

+0

我認爲@iAmRubuuu想要了解單身人士課程。 – 2013-03-16 16:34:54

+0

順便說一句,我會在幾天後發佈一篇博文,並會嘗試回答這些問題。 – 2013-03-16 16:35:44

回答

2

你在正確的軌道上。

1)當尋找單身類中的方法,你想用instance_methods,不methods:「實例方法定義」,而

foo_sing.instance_methods.include? :bar # => true 
# or 
foo_sing.method_defined? :bar # => true 

這是一個有點混亂,因爲method_defined?的真正含義, methods真的意思是singleton methods ...

2)你不能繼承或實例化一個單例類,因爲它意味着是一個單例,即只有一個實例。

無論如何,這並不重要,因爲您應該使用mixin代碼來重用。這些可以包括/預裝在儘可能多的單身人士班或普通班,只要你想:

foo.extend ResuableFunctionality 
# or equivalently: 
class << foo 
    include ReusableFunctionality 
end 
+0

當然,我會的。我想看看所有的答案或更多。如果你把它寫在你的帖子上,那會很棒。 :) – 2013-03-16 16:41:09