I’m just learning Ruby and have and have an extremely beginner question. Is the difference between the four types of variables mainly just scope. So local variables can only be used within the current block, instance variables within the current instance, global variables within every scope and finally, class variables within the current class? Thanks a lot!
Share
You’ve got it right although there are some
wrinkles. Class variables (@@foo) can be accessed both from the class methods and the instance methods of a class.
They behave somewhat unintuitively with respect to inheritance: if you set such a variable in a base class and set it again in the subclass then you will change the value for all classes in the hierarchy. If you’re using class variables to store settings this is often not what you want – you want subclasses to be able to “override” values from the base class without actually changing them for the base class. Rails provides
class_attributefor this: it creates accessor methods which have that behaviour.Finally, not really a separate type, but since classes are objects there are also class instance variables. These don’t do anything with respect to inheritance – each class object in a hierarchy has its own completely independant ones. Unlike class variables, instances can’t directly manipulate class instance variables.