我試圖在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
>>
您不能使用接收器訪問'new',因爲它現在是私人的。而你是把它變成私人的。不清楚你爲什麼做這樣矛盾的事情,並想知道它。 – sawa
不知道爲什麼這是投票。 @sawa,有java背景的人可以很容易地犯這個錯誤,我認爲這個問題可以對他們有幫助。在JAVA中,我們可以訪問類聲明中的任何私有內容, – GingerJim
Ruby不是Java。如果不知道它的作用,請不要使用方法。不閱讀文件只是懶惰。 – sawa