Question
In Ruby on Rails, what is the difference between @title and title? Both appear to be valid variable names. How do I decide when to use a variable with @ and when to use one without it?
Short Answer
By the end of this page, you will understand the difference between instance variables like @title and local variables like title in Ruby and Ruby on Rails. You will learn how scope works, why Rails views often use @variables, and how to choose the right kind of variable in controllers, views, and methods.
Concept
In Ruby, the @ symbol changes the kind of variable you are using.
titleis a local variable@titleis an instance variable
These are not the same variable.
Local variables
A local variable exists only within the current scope, such as:
- a method
- a block
- a small section of code
Example:
def show_name
name = "Ruby"
puts name
end
Here, name only exists inside show_name.
Instance variables
An instance variable belongs to a specific object instance. It can usually be accessed by different methods of that same object.
Example:
class Book
def set_title
@title = "Eloquent Ruby"
end
def print_title
puts @title
end
end
If runs first, can use the same because both methods are working with the same object.
Mental Model
Think of local and instance variables like storage places in a house.
titleis like a note on your desk. Only the person currently sitting there can use it.@titleis like a label attached to the room. Anyone working in that room later can still see it.
In Rails:
- a controller action can create
@title - the matching view can read that same
@title
But a local variable like title is temporary. It stays only inside the method where it was created.
So if you need data only for a few lines, use a local variable. If you need data to stay attached to the current controller object and be visible to the view, use an instance variable.
Syntax and Examples
Basic syntax
title = "Hello" # local variable
@title = "Hello" # instance variable
Local variable example
def greeting
message = "Welcome"
puts message
end
message exists only inside the greeting method.
Instance variable example
class Greeting
def set_message
@message = "Welcome"
end
def show_message
puts @message
end
end
g = Greeting.new
g.set_message
g.show_message
Output:
Welcome
@message is stored in the object, so one method can set it and another can read it.
Step by Step Execution
Consider this Rails controller action:
class PagesController < ApplicationController
def home
title = "Local title"
@title = "Instance title"
end
end
And this view:
<p><%= @title %></p>
<p><%= title %></p>
What happens step by step
- Rails receives a request for the
homeaction. - Rails creates a controller object for that request.
- Inside
home,title = "Local title"creates a local variable. - That local variable exists only inside the
homemethod. @title = "Instance title"creates an instance variable on the controller object.- The action finishes.
- Rails renders the view connected to that action.
- The view can access
@titlebecause it is attached to the controller instance. - The view cannot access
titlebecause the local variable stopped existing when the method ended.
Result
Real World Use Cases
In Rails controllers
A controller fetches data and exposes it to the view.
def show
@post = Post.find(params[:id])
end
The view can then display @post.
In forms and edit pages
def edit
@user = User.find(params[:id])
end
The form uses @user to fill in existing values.
For temporary calculations inside a method
def total_price
subtotal = 100
tax = 10
subtotal + tax
end
subtotal and tax are local variables because they are only needed inside that method.
In Ruby classes outside Rails
Instance variables store object state.
Real Codebase Usage
In real Rails projects, developers usually prefer local variables by default and use instance variables only when data must be shared with the view or across methods of the same object.
Common controller pattern
class ProductsController < ApplicationController
def show
@product = Product.find(params[:id])
end
end
This is standard because the view needs @product.
Common service or model pattern
def discounted_price(price)
discount = 0.2
price - (price * discount)
end
discount stays local because nothing outside the method needs it.
Using instance variables for object state
class ReportBuilder
def initialize(records)
@records = records
end
.map(&)
Common Mistakes
1. Expecting a local variable to be available in the view
Broken example:
class PostsController < ApplicationController
def index
title = "Posts"
end
end
<h1><%= title %></h1>
Why it fails:
titleis local to the controller method- the view cannot access it
Fix:
def index
@title = "Posts"
end
2. Using instance variables for everything
Broken style:
def sum
@x = 1
@y = 2
@z = @x + @y
end
Why it is a problem:
Comparisons
| Variable type | Example | Scope | Common Rails use |
|---|---|---|---|
| Local variable | title | Only within the current method or block | Temporary calculations, helper values |
| Instance variable | @title | Available to the current object across methods | Passing data from controller to view |
Local variable vs instance variable
- Local variable: short-lived and limited in scope
- Instance variable: attached to an object and available to that object's methods
In a Rails controller
| Code | Available in view? |
|---|---|
title = "Hello" | No |
Cheat Sheet
name = "Ruby" # local variable
@name = "Ruby" # instance variable
nameand@nameare different variables- Local variables exist only in the current method or block
- Instance variables belong to an object
- In Rails controllers, instance variables are available in views
- Use local variables for temporary values
- Use instance variables for shared object state or controller data for templates
- Unset instance variables are
nil
Quick rule
- Need it only inside one method? Use
title - Need it in the view or across object methods? Use
@title
Rails example
def show
@post = Post.find(params[:id]) # view can use this
post_count = 5 # view cannot use this
end
Common error
<%= title %>
FAQ
What does @ mean before a variable in Ruby?
It means the variable is an instance variable, which belongs to a specific object.
What is the difference between title and @title in Rails?
title is a local variable and only exists in the current scope. @title is an instance variable and is available to the controller object and its view.
Why do Rails views often use @variables?
Because Rails exposes controller instance variables to the view template for rendering.
Should I always use @variables in a Rails controller?
No. Use instance variables only for data the view needs. Use local variables for temporary values inside the action.
What happens if I use an instance variable without setting it?
Its value is nil.
Can two methods in the same class use the same instance variable?
Yes, if they run on the same object instance.
Is @title the same as a global variable?
No. A global variable starts with $, not @. Instance variables are limited to one object.
Mini Project
Description
Build a small Rails-style example that shows which variables are available inside a method and which are available in a view. This project helps you practice the difference between local variables and instance variables in a realistic controller/view setup.
Goal
Create a controller action that sends a page title and a list of posts to a view using instance variables, while keeping temporary calculations as local variables.
Requirements
- Create a controller action named
index - Store the page title in an instance variable
- Store a list of post titles in an instance variable
- Use at least one local variable for a temporary calculation
- Render the instance variables in an ERB view
Keep learning
Related questions
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.
Convert a Unix Timestamp to Ruby DateTime
Learn how to convert Unix timestamps to Ruby DateTime and Time objects, with examples, differences, pitfalls, and practical Ruby usage.