为什么可以在Ruby中显式调用私有类方法?

时间:2015-06-09 07:28:14

标签: ruby private

众所周知,私有方法无法使用ruby中的显式接收器进行调用。但是当我定义一个类时,我可以通过类本身调用私有类方法。

例如:

class A
   private
     def self.test
        puts "hello,world!"
     end
end

A.test => hello,world!
A.new.test NoMethodError: private method `test' called for #<A:0x007f80b91a10f8>

与私人定义相矛盾。任何人都可以告诉我原因。提前谢谢!

2 个答案:

答案 0 :(得分:8)

private仅影响实例方法。要创建私有类方法,请使用private_class_method

class A
   private_class_method def self.test
      puts "hello,world!"
   end
end

class A
   def self.test
      puts "hello,world!"
   end
   private_class_method :test
end

编辑:另一种方法是在元类上定义方法 - 它们将表现为类方法。

class A
  class << self
    private
    def test
      puts "hello,world!"
    end
  end
end

不幸的是,没有protected_class_method这样的东西 - 但最后一个选项给了我们一个如何做的提示:

class A
  class << self
    protected
    def test
      puts "hello,world!"
    end
  end
end

但请注意,它只能从后代类的类方法中调用:

class B < A
  def self.test_class
    A.test
  end
  def test_instance
    A.test
  end
end

B.test_class
# => hello,world!
B.new.test_instance
# => `test_instance': protected method `test' called for A:Class (NoMethodError)

答案 1 :(得分:3)

def self.test声明类方法,而不是实例方法。要将类方法设为私有,您需要使用private_class_method,而不是private