[ACCEPTED]-Constants or class variables in ruby?-class-variables
The main thing is that by using the CONSTANT 4 notation, you're making it clear to the 3 reader. the lower case, frozen string gives 2 the impression is might be settable, forcing 1 someone to go back and read the RDoc.
If these are really constant values that 6 you define in source code and do not want 5 to change during code execution then I would 4 recommend to use constant.
If you plan to 3 set and/or change these values dynamically 2 during execution then use class variable 1 with getters and setters.
Basically, you could put it like this: If 6 you want something that's constant, use 5 a constant. If you want something that's 4 variable, use a variable. It seems like 3 your list of types are constants, seeing 2 it is a frozen array, so I would say it 1 makes sense to use a constant in this case.
If you don't want the value to ever change 11 during the runtime of your program, and you 10 are comfortable with allowing the value 9 to be accessed outside of your class, use 8 a constant.
Otherwise, you can use a class 7 variable. However, be aware that class variables 6 are shared among subclasses and instances 5 of subclasses. So if you might at some point 4 in the future implement a child class, you 3 have to be very careful about your use of 2 class variables.
Refer to the answers here 1 for more on this: Class variables in Ruby
Note that class variables are private to 3 a class and its instances (cf. http://phrogz.net/programmingruby/tut_classes.html). However, if 2 you want to make your constant private you 1 can always do:
FOO = 18 private_constant :FOO
More Related questions