Ruby variables & assignment
This course covers variables and assignment in Ruby. It starts with what a variable is: a name linked to a value, created by assignment with no keyword or declared type. It then covers the naming rules for local variables, the snake_case convention, and the difference between = for assignment and == for comparison. Later lessons explain local scope inside methods, instance variables written with @, and how undefined local variables raise a NameError while unset instance variables return nil. A small BankAccount class combines both kinds of variable.
What you'll learn
- ✓What a variable is and how reassignment changes its value
- ✓Naming rules for local variables and the snake_case convention
- ✓The difference between = for assignment and == for comparison
- ✓Local scope in methods, with parameters and return values crossing it
- ✓Instance variables with @ and how they persist on each object
- ✓How undefined locals and unset instance variables behave, and checking with nil?
What a variable actually is
The last course was all mindset, with no code to run. This one changes that. Variables are the first concrete Ruby syntax in this series, and everything after builds on them.
Read the full lesson free →Curriculum
7 lessonsWhat a variable actually is
A variable is a name linked to a value, created by assignment without keywords or declared types.
Local variables: naming and snake case
Local variable names start with a lowercase letter or underscore, and Ruby's convention is descriptive snake_case.
Assignment is not equality: = vs ==
The = operator assigns a value, while == compares and returns true or false, plus chained assignment.
Local scope: where a variable lives and dies
Each method creates its own local scope, and values cross it only through parameters and return values.
Instance variables: @
Instance variables written with @ belong to an object, persist across its method calls, and differ per object.
nil and undefined variables
An undefined local variable raises a NameError, while an unset instance variable returns nil, checkable with nil?.
Putting it together: tracking state with local and instance variables
A small BankAccount class combines local and instance variables to track a balance across method calls.