Variables & Scope
Learn what variables are, why we use them, and how to work with different types of variables in Ruby.
What is a Variable?
Think of a variable like a labeled box: You put something inside the box and give it a name so you can find it later.
Real-World Example
Why Use Variables?
- Reusability: Use the same value multiple times without retyping
- Readability: Give meaningful names to make code easier to understand
- Flexibility: Change values easily without finding every occurrence
- Organization: Keep related data together
Types of Variables
Ruby has 4 main types of variables: Each type has different rules about where you can use them and how long they last.
local Local Variables
Like a sticky note: Only visible in the current room (method/block). Start with lowercase letter.
@instance Instance Variables
Like a personal locker: Belongs to one specific object. Start with @ symbol.
@@class Class Variables
Like a shared bulletin board: All objects of the same class can see and use it. Start with @@.
$global Global Variables
Like a city-wide announcement: Everyone can see it, but use sparingly! Start with $.
Understanding Scope
Scope = Where you can see and use a variable: Think of it like different rooms in a house - some things are only visible in certain rooms.
Scope Example
Naming Your Variables
Good variable names make your code readable: Choose names that clearly describe what the variable contains.
Good Names
user_name- clear and descriptivetotal_count- explains what it countsis_authenticated- boolean (true/false)email_address- specific purpose
Avoid These
x- too vaguetemp- temporary for what?data- what kind of data?stuff- meaningless
Best Practices
Variable Best Practices
- Start with local variables: Use them most of the time
- Use descriptive names: Make your code self-documenting
- Initialize variables: Give them a starting value
- Use the right type: Choose the appropriate variable type for your needs
- Avoid global variables: They can cause confusion and bugs
Common Mistakes to Avoid
- Using variables before defining them: Always assign a value first
- Poor naming: Use clear, descriptive names
- Forgetting scope: Variables only exist where you create them
- Overusing global variables: They make code hard to debug
- Not initializing variables: Can lead to unexpected errors
What You've Learned
Key Takeaways
- Variables are like labeled boxes: They store data with a name
- Four main types: local, instance (@), class (@@), and global ($)
- Scope matters: Variables only exist where you create them
- Good naming is crucial: Make your code readable and self-documenting
- Start simple: Use local variables most of the time
Try It Yourself - Interactive Practice
Learning Tip: The best way to master variables is through hands-on practice! Try these exercises step by step. Experiment with different values and see what happens!