Ruby私有类方法

时间:2013-07-15 08:56:21

标签: ruby

我试图在ruby中实现单例模式,只是想知道为什么我无法访问ruby中的私有类方法

class Test

    private_class_method :new
    @@instance = nil
    def self.getInstance
            if(!@@instance)
                    @@instance = Test.new
            end

            return @@instance
    end
end

我将“new”声明为私有类方法,并尝试在我的单例方法中调用“new”“getInstance”

测试输出

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

private_class_method :new

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

这就是原因。私有方法不能使用显式接收器调用。尝试使用send

@@instance = Test.send(:new)

或使用隐式接收器(因为selfTest

@@instance = new