ruby 中的常量或类变量?
我已经用 Ruby 编程几个月了,我想知道什么时候适合在类变量上使用常量,反之亦然。 (我正在 Rails 中工作,思考模型中的常量)。
class Category
TYPES = %w(listing event business).freeze
end
或者
class Category
@@types = %w(listing event business).freeze
cattr_reader :types
end
是否存在一种情况比另一种更可取的情况? 或者这只是品味/风格的问题?
I've been programming in Ruby for a few months now, and I'm wondering when it is appropriate to use constants over class variables and vice versa. (I'm working in Rails, thinking about constants in models).
class Category
TYPES = %w(listing event business).freeze
end
OR
class Category
@@types = %w(listing event business).freeze
cattr_reader :types
end
Are there circumstances where one is preferable to another? Or is it just a matter of taste/style?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最重要的是,通过使用 CONSTANT 符号,您可以让读者清楚地了解这一点。 小写的冻结字符串给人的印象是可能是可设置的,迫使某人返回并阅读 RDoc。
The main thing is that by using the CONSTANT notation, you're making it clear to the reader. the lower case, frozen string gives the impression is might be settable, forcing someone to go back and read the RDoc.
如果这些确实是您在源代码中定义的常量值并且不想在代码执行期间更改,那么我建议使用常量。
如果您计划在执行期间动态设置和/或更改这些值,则将类变量与 getter 和 setter 一起使用。
If these are really constant values that you define in source code and do not want to change during code execution then I would recommend to use constant.
If you plan to set and/or change these values dynamically during execution then use class variable with getters and setters.
基本上,您可以这样说:如果您想要恒定的东西,请使用常量。 如果您想要可变的东西,请使用变量。 看起来你的类型列表是常量,因为它是一个冻结数组,所以我想说在这种情况下使用常量是有意义的。
Basically, you could put it like this: If you want something that's constant, use a constant. If you want something that's variable, use a variable. It seems like your list of types are constants, seeing it is a frozen array, so I would say it makes sense to use a constant in this case.
请注意,类变量对于类及其实例来说是私有的(参见 http://phrogz.net/programmingruby /tut_classes.html)。 但是,如果您想将常量设为私有,您可以随时执行以下操作:
Note that class variables are private to a class and its instances (cf. http://phrogz.net/programmingruby/tut_classes.html). However, if you want to make your constant private you can always do:
如果您不希望该值在程序运行时发生变化,并且您愿意允许在类外部访问该值,请使用常量。
否则,您可以使用类变量。 但是,请注意,类变量在子类和子类实例之间共享。 因此,如果您可能在将来的某个时候实现子类,则必须非常小心地使用类变量。
有关更多信息,请参阅此处的答案:Ruby 中的类变量
If you don't want the value to ever change during the runtime of your program, and you are comfortable with allowing the value to be accessed outside of your class, use a constant.
Otherwise, you can use a class variable. However, be aware that class variables are shared among subclasses and instances of subclasses. So if you might at some point in the future implement a child class, you have to be very careful about your use of class variables.
Refer to the answers here for more on this: Class variables in Ruby