简体   繁体   中英

What is the difference between local variables, instance variables, global variables, and class variables?

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!

You got it right. The difference is just the scope.

Glad you were able to figure this out intuitively. The difference is just scope (however the way they are dealt with in memory is pretty different).

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_attribute for 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM