2013-07-15 107 views
2

我試圖在Ruby中實現一個單件模式,只是想知道爲什麼我不能訪問紅寶石私有的類方法Ruby的私有類方法

class Test 

    private_class_method :new 
    @@instance = nil 
    def self.getInstance 
      if([email protected]@instance) 
        @@instance = Test.new 
      end 

      return @@instance 
    end 
end 

我宣佈「新」作爲一個私有的類方法,以及嘗試致電 「新」 在我的單身法 「的getInstance」

測試輸出

>> require "./test.rb" 
=> true 
>> Test.getInstance 
NoMethodError: private method `new' called for Test:Class 
from ./test.rb:7:in `getInstance' 
from (irb):2 
>> 
+0

您不能使用接收器訪問'new',因爲它現在是私人的。而你是把它變成私人的。不清楚你爲什麼做這樣矛盾的事情,並想知道它。 – sawa

+1

不知道爲什麼這是投票。 @sawa,有java背景的人可以很容易地犯這個錯誤,我認爲這個問題可以對他們有幫助。在JAVA中,我們可以訪問類聲明中的任何私有內容, – GingerJim

+1

Ruby不是Java。如果不知道它的作用,請不要使用方法。不閱讀文件只是懶惰。 – sawa

回答

3

::new由於是一個私有方法,可以不通過將消息發送到類恆定訪問它。儘管如此,它只會通過省略接收器將它發送到隱含的self

此外,由於這是一個類方法,因此它的實例變量範圍已經是類級別的,因此您不需要使用@@類變量。一個實例變量在這裏工作得很好。

class Test 
    private_class_method :new 

    def self.instance 
    @instance ||= new 
    end 
end 


puts Test.instance.object_id 
puts Test.instance.object_id 
# => 33554280 
# => 33554280 
2
private_class_method :new 

NoMethodError: private method `new' called for Test:Class 

那爲什麼。私有方法不能用明確的接收方調用。嘗試使用send

@@instance = Test.send(:new) 

或隱式接收器(因爲selfTest

@@instance = new