Constants or class variables in ruby?

RubyConstantsClass Variables

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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.

Solution 3 - Ruby

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.

Solution 4 - 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: https://stackoverflow.com/questions/10594444/class-variables-in-ruby

Solution 5 - Ruby

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:

FOO = 18
private_constant :FOO

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen CrouseView Question on Stackoverflow
Solution 1 - RubyCharlie MartinView Answer on Stackoverflow
Solution 2 - RubyRaimonds SimanovskisView Answer on Stackoverflow
Solution 3 - RubyAugust LilleaasView Answer on Stackoverflow
Solution 4 - RubyawolfsonView Answer on Stackoverflow
Solution 5 - RubyberkosView Answer on Stackoverflow