首页 > 解决方案 > 用另一个相同的类调用一个私有类方法

问题描述

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

标签: ruby

解决方案


方法体中的方法Module#private单独一行,导致其后定义的所有实例方法private直到并且如果Module#publicModule#protected方法单独出现在一行上1。类方法定义不受影响。

以下是使类方法私有的三种方法。

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

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

类的单例类中的私有实例方法是私有类方法。请参阅Object#singleton_classModule#private_method_defined?.

#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在类的单例类中定义实例方法时包含关键字in-line

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#private如果实例方法是用publicprotected 内联定义的(例如,public def meth... ,则当然忽略单独一行。


推荐阅读