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
解决方案
方法体中的方法Module#private单独一行,导致其后定义的所有实例方法private
直到并且如果Module#public或Module#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_class和Module#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
如果实例方法是用public
或protected
内联定义的(例如,public def meth...
) ,则当然忽略单独一行。
推荐阅读
- php - php数据验证提交错误数据
- java - 如何在java中解析和获取xml中的数据
- c# - Parallel.ForEach 在完成之前退出
- qt - 顶部圆形透明窗
- c++ - 找不到函数的c ++错误标识符?
- protractor - 在量角器的 BeforeAll 函数中执行 2 个查询时无法获取正确的数据
- java - 嵌套类@Configuration @Bean 创建中的spring Bean Overriding 2.1.x 失败,并显示“已经定义了具有该名称的bean”
- python - QTableView点击信号从未发出?
- visual-studio - 原生可视化器能否根据其集合的参数名称修改项目的显示?
- sdk - gsutil 路径名未从命令行传递到目标存储桶