Ruby Fundamentals: Properties & Variables
Master Ruby fundamentals with objects, properties and variables
Core Ruby Concepts You'll Master
Properties of Objects
Learn how objects have attributes like adjectives describing their characteristics. Properties are variables attached to objects that define their state.
Instance Variables
Discover variables with @ signs that can be accessed by any method throughout the class. Essential for sharing data across methods.
Local Variables
Understand variables without @ signs that exist only within their own method. Critical for method-specific data storage.
You'll need Terminal access and IRB (Interactive Ruby) to follow along. If you've closed Terminal or exited IRB, open a new Terminal window and type the irb command to get started.
Variable Names vs Object Properties
| Feature | Variable Names | Object Properties |
|---|---|---|
| Cat References | fluffy, george | Miss Fluffy, Mr George |
| Perspective | External reference | Internal identity |
| Purpose | Code organization | Object state |
Creating Objects with Properties
Define initialize method
The initialize method is automatically called when creating new objects. It accepts parameters that become object properties.
Set instance variables
Use @name syntax to create instance variables that store object properties and can be accessed by other methods.
Create accessor methods
Define methods like say_name that return instance variables, allowing objects to share their properties.
You can set default values for parameters using name = 'Kitty' syntax. This prevents errors when objects are created without required parameters and provides fallback values.
Instance vs Local Variables
| Feature | Instance Variables | Local Variables |
|---|---|---|
| Syntax | @variable_name | variable_name |
| Scope | Throughout the class | Within method only |
| Access | Any method can use | Same method only |
| Example | @remember_this | forget_this |
When to Use Each Variable Type
Attempting to access a local variable from a different method results in NameError: undefined local variable. This demonstrates the scope limitation of local variables.
Later when you get to Rails you'll see that instance variables are often used to share data between controllers and views.
Key Takeaways