我试图在 ruby 中实现单例模式,只是想知道为什么我无法在 ruby 中访问私有类方法
class Test
private_class_method :new
@@instance = nil
def self.getInstance
if(!@@instance)
@@instance = Test.new
end
return @@instance
end
end
我将“new”声明为私有类方法,并尝试在我的单例方法“getInstance”中调用“new”
测试输出
>> require "./test.rb"
=> true
>> Test.getInstance
NoMethodError: private method `new' called for Test:Class
from ./test.rb:7:in `getInstance'
from (irb):2
>>