Ruby Variables — Complete Beginner Guide
Learning Objectives
- Create and update Ruby variables
- Distinguish local, instance, class, and global variables
- Follow Ruby naming conventions
- Predict how variable scope affects access
- Store and reuse values confidently
What Is a Variable
A variable is a named container for a value. Instead of repeating data throughout your program, you store it once and refer to it by name. When the underlying value changes, every reference reflects that update automatically.
Create variables with simple assignment:
name = "Ava"
age = 28
height = 5.6
After assignment, name refers to a string, age to an integer, and height to a float. Ruby figures out the type automatically, so you never declare types explicitly the way you would in some other languages.
Local Variables
Local variables exist only inside the method, block, or top-level scope where they were created. This is the type you will use most often while learning and building everyday scripts.
def greet
message = "Welcome back"
puts message
end
greet
puts message
The second puts fails because message is not visible outside greet. Scope keeps names from colliding and makes larger programs easier to reason about when many methods share similar names.
Rules for local variables:
- Must start with a lowercase letter or underscore
- Exist only within their defining scope
- Are undefined until first assignment
Instance Variables
Instance variables belong to a specific object. Every object keeps its own copies, and each begins as nil until you assign a value. In Ruby, instance variable names start with the at symbol.
class User
def initialize(name)
@name = name
end
def intro
puts "I am " + @name
end
end
u = User.new("Ben")
u.intro
Instance variables are accessible inside the object's methods. They store state that individual objects need to remember between method calls, which is fundamental to object-oriented design.
Class Variables
Class variables are shared across an entire class and all of its instances. Their names begin with two at symbols. Use them for data that should stay consistent for every object of that class.
class Counter
@@count = 0
def initialize
@@count += 1
end
def self.total
@@count
end
end
Counter.new
Counter.new
puts Counter.total
Because the variable is shared, creating two instances reports two. Class variables are powerful but should be used sparingly, since shared mutable data can surprise you as programs grow larger.
Global Variables
Global variables begin with the dollar sign and can be accessed from anywhere in the program once defined.
$app_name = "LearnRuby"
def show_name
puts $app_name
end
show_name
puts $app_name
Globals are convenient for rare application-wide settings, but overusing them makes data flow hard to track. Prefer passing values as method parameters whenever that is practical for your design.
Comparison Table
| Type | Prefix | Scope | Typical use |
|---|---|---|---|
| Local | none | Current scope | Everyday calculations |
| Instance | at sign | Current object | Object state |
| Class | double at sign | Entire class hierarchy | Shared class data |
| Global | dollar sign | Entire program | Rare application settings |
Variable Naming Conventions
Ruby enforces some naming rules and follows community style for others. Learning both makes your code feel natural to other Rubyists.
Required rules
- Local and instance variables cannot start with a digit
- Globals must start with the dollar sign
- Class variables must start with two at signs
- Constants start with an uppercase letter instead
Recommended style
- Use snake_case for variables and methods: user_name, total_price
- Avoid single letters except in tiny loops with obvious meaning
- Choose names that describe purpose, not type: price rather than num
Readable names make debugging faster and help teammates understand your intent at a glance during code reviews.
Reassignment and Mutation
Reassignment simply points the variable at a new value without any ceremony:
score = 10
score = score + 5
puts score
You can also use the plus-equals shortcut to update values in place more concisely. Understanding that variables are references becomes especially important when you study arrays and hashes in upcoming lessons.
Scope and Lifetime
Variables only exist within the region of code where they were created. Local variables defined inside a method disappear once that method returns, while variables defined at the top level of a script live for the entire run. Understanding scope prevents bugs where you accidentally reference a variable that has already gone out of existence.
Key Takeaways
💡
- Variables store values so you can reuse and update them
- Local variables are confined to their scope; instance variables live on objects
- Class variables are shared across a class; globals work program-wide
- Follow snake_case naming for readable, idiomatic Ruby
- Uninitialized variables return nil instead of raising an error
Practice Questions
- What is the difference between a local variable and an instance variable?
- Which symbol or symbols prefix a class variable?
- Why might relying on global variables make code hard to maintain?
- Write a method that creates a local variable and prints it.
- Convert these names to snake_case: userName, totalPrice, isActive.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions