Variables & Constants

Master Ruby variable types: local, instance, class, and global variables, plus constants.

Beginner 1 min read

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

# Imagine you have a box labeled "my_name"
my_name = "Sarah"
# Now the box contains "Sarah"

# You can look inside the box anytime
puts my_name
# This prints: Sarah

# You can change what's in the box
my_name = "John"
puts my_name
# Now this prints: John

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.

# Examples
name = "Alice"
age = 25
is_student = true

@instance Instance Variables

Like a personal locker: Belongs to one specific object. Start with @ symbol.

# Examples
@name = "Bob"
@email = "bob@email.com"
@is_active = true

@@class Class Variables

Like a shared bulletin board: All objects of the same class can see and use it. Start with @@.

# Examples
@@total_users = 0
@@version = "1.0"
@@settings = {}

$global Global Variables

Like a city-wide announcement: Everyone can see it, but use sparingly! Start with $.

# Examples
$debug = true
$program_name = "MyApp"
$stdout

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

# Global variable - visible everywhere
$app_name = "My Ruby App"

# Class variable - shared by all objects of this class
class User
@@total_users = 0

def initialize(name)
# Instance variable - belongs to this specific user
@name = name
@@total_users += 1

# Local variable - only exists in this method
greeting = "Hello, #{@name}!"
puts greeting
end
end

# Create users
user1 = User.new("Alice")
user2 = User.new("Bob")
puts "Total users: #{User.class_variable_get(:@@total_users)}"

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 descriptive
  • total_count - explains what it counts
  • is_authenticated - boolean (true/false)
  • email_address - specific purpose

Avoid These

  • x - too vague
  • temp - 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!

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...