用同一个类的另一个调用一个私有类方法

时间:2019-11-12 16:48:01

标签: ruby

class Person
  def self.first_name
    puts "this is the first_name"
    second_name
  end
  private
  def self.second_name
    third_name
  end
  def self.third_name
    puts "this is the third name"
  end
end

如何使self.second_name在私有方法中调用self.third_name

1 个答案:

答案 0 :(得分:3)

方法Module#private在方法主体中本身就单独导致一行,此后定义的所有 instances方法private,直到方法{ {3}}或Module#public单独出现在一行上 1 。类方法的定义不受影响。

以下三种将类方法设为私有的方法。

#1。使用方法Module#protected将公共类方法设为私有

class Klass
  def self.class_meth1
    '#1'
  end
  private_class_method(:class_meth1)
end

Klass.class_meth1
  #=> NoMethodError (private method `class_meth1' called for Klass:Class)
Klass.send(:class_meth1)
  #=> "#1" 
Klass.singleton_class.private_method_defined?(:class_meth1)
  #=> true

类的单例类中的私有实例方法是私有类方法。参见Module#private_class_methodObject#singleton_class

#2。在关键字private

之后的类的单例类中定义实例方法
class Klass
  class << self
    private
    def class_meth2
      '#2'
    end 
  end
end

Klass.singleton_class.private_method_defined?(:class_meth2)
  #=> true

#3。在类的单例类中定义实例方法时,内嵌关键字private

class Klass
  class << self
    private def class_meth3
      '#3'
    end 
  end
end

Klass.singleton_class.private_method_defined?(:class_meth3)
  #=> true

请注意,private在下面没有任何作用,它创建了一个公共类方法:

class Klass
  private def self.class_meth
  end
end

调用私有类方法

鉴于前面的讨论,这就是您所需要的。

class Person
  def self.first_name
    puts "this is the first_name"
    second_name  
  end
  class << self
    private
    def second_name
      third_name
    end
    def third_name
      puts "this is the third name"
    end
  end
end

Person.first_name
this is the first_name
this is the third name

1。如果使用Module#privatepublic inline (例如protected)定义了实例方法,则当然不用理会在线上的public def meth... / sup>。