tags:

views:

441

answers:

3

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?

+13  A: 

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.

Charlie Martin
+1 - and think of the poor variable that doesn't get to fulfil its desiny (it never varies)! Related to the RDoc comment, note that constants get documented by default
Gareth
Poor little unloved variable.
Charlie Martin
+3  A: 

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.

Raimonds Simanovskis
+1  A: 

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.

August Lilleaas