Constants or class variables in ruby?

后端 未结 5 1868
闹比i
闹比i 2020-12-30 18:37

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,

5条回答
  •  庸人自扰
    2020-12-30 19:21

    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

提交回复
热议问题