如何在Ruby中制作私有类常量 [英] How to I make private class constants in Ruby
本文介绍了如何在Ruby中制作私有类常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby中,如何创建一个私有类常量?
(即在班级内部可见但在班级外部不可见)
In Ruby how does one create a private class constant? (i.e one that is visible inside the class but not outside)
class Person
SECRET='xxx' # How to make class private??
def show_secret
puts "Secret: #{SECRET}"
end
end
Person.new.show_secret
puts Person::SECRET # I'd like this to fail
推荐答案
您也可以将常量更改为类方法:
You can also change your constant into a class method:
def self.secret
'xxx'
end
private_class_method :secret
这使得在所有实例中均可访问类,但不在外面。
This makes it accessible within all instances of the class, but not outside.
这篇关于如何在Ruby中制作私有类常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文