如何在 Ruby 中创建私有类常量
在 Ruby 中如何创建私有类常量? (即在班级内部可见但外部不可见)
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 ruby 1.9.3 开始,您拥有
Module#private_constant
方法,这似乎正是您想要的:Starting on ruby 1.9.3, you have the
Module#private_constant
method, which seems to be exactly what you wanted:您还可以将常量更改为类方法:
这使得它可以在类的所有实例中访问,但不能在外部访问。
You can also change your constant into a class method:
This makes it accessible within all instances of the class, but not outside.
您可以使用 @@class_variable 代替常量,它始终是私有的。
当然,然后 ruby 不会采取任何措施来强制 @@secret 的恒定性,但是 ruby 几乎不会采取任何措施来强制强制恒定性,所以......
Instead of a constant you can use a @@class_variable, which is always private.
Of course then ruby will do nothing to enforce the constantness of @@secret, but ruby does very little to enforce constantness to begin with, so...
嗯...
有点作品。
Well...
kind of works.
您可以首先将其设为私有方法
You can just literally make it a private method in the first place ????????♂️