What are local, instance, class, and global variables in Ruby?
Updated May 17, 2026
Short answer
Local variables start with lowercase/underscore; instance variables with @; class variables with @@; and global variables with $. Each has a distinct scope bound to blocks/methods, instances, classes, or the entire runtime.
Deep explanation
Local variables are scoped strictly to the current method, block, or module where they are defined. Instance variables (@) belong to a single instance of an object and are accessible across all instance methods within that object. Class variables (@@) are shared across an entire class hierarchy, meaning a change in a subclass alters the value for the parent class too. Global variables ($) are accessible anywhere within the Ruby process runtime.
Real-world example
Instance variables are heavily used in Rails controllers to pass data down to views. Local variables are preferred inside loops and method definitions to avoid polluting the object state.
Common mistakes
- Overusing class variables (`@@`). Because they are shared across inheritance trees, a subclass redefining a class variable will accidentally mutate the state of the parent class, introducing sneaky bugs.
Follow-up questions
- What is preferred over class variables for class-level configuration?
- What does an uninitialized instance variable evaluate to?