🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Ruby Variables — Complete Beginner Guide

Ruby BasicsRuby Variables🟢 Free Lesson

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

TypePrefixScopeTypical use
LocalnoneCurrent scopeEveryday calculations
Instanceat signCurrent objectObject state
Classdouble at signEntire class hierarchyShared class data
Globaldollar signEntire programRare 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

  1. What is the difference between a local variable and an instance variable?
  2. Which symbol or symbols prefix a class variable?
  3. Why might relying on global variables make code hard to maintain?
  4. Write a method that creates a local variable and prints it.
  5. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Ruby Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement