有什么方法可以从包含的模块访问私有(private)常量吗?
这是我想做的:
module B
def access_private_here
puts MY_CONST
end
end
class A
include B
private
MY_CONST = 1
end
我知道如果这个常量是公开的,我可以做 self.class::MY_CONST
,有什么方法可以用私有(private) cons 实现同样的效果吗?
最佳答案
我建议这样写,这样当你重命名 B
时,除了 include B
之外你不需要改变任何东西:
module B
def access_private_here
puts self.class::MY_CONST
end
end
class A
include B
private
MY_CONST = "cat"
end
A.new.access_private_here #=> "cat"
关于ruby - 从模块访问私有(private)常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026085/