Ruby provides a number of options for non-instance-specific variables – class variables (of the form:
@@var), constants (in all caps:
VAR), and class instance variables (
@var). Which one to use depends on the use case, and to some degree on personal preference. Let’s explore this a bit.
Constants are meant to be – well, constant. This is not technically enforced in Ruby; if you redefine a constant during program execution, it will display a warning, but not actually raise an error. However, the semantic idea of a constant is that it should be defined once and not touched again. Variables, on the other hand, are variable. They record a particular state that is likely to be redefined at some future point in time.
Now let’s examine some use cases and see where things start to get tricky. To make things fun, let’s go to the zoo!