Bird
Raised Fist0
Rubyprogramming~10 mins

Instance variables (@) in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Instance variables (@)
Create Object
↓
Initialize Instance Variables
↓
Use Instance Variables in Methods
↓
Access or Modify Instance Variables
↓
Object Maintains Its Own Data
When an object is created, instance variables start with @ and store data unique to that object. Methods can read or change these variables.
Execution Sample
Ruby
class Person
  def initialize(name)
    @name = name
  end
  def greet
    "Hello, #{@name}!"
  end
end
p = Person.new("Anna")
p.greet
Creates a Person object with a name stored in @name, then greets using that name.
Execution Table
StepActionInstance Variable @nameOutput
1Create Person object with name 'Anna'nil -> 'Anna'
2Call greet method'Anna'"Hello, Anna!"
3End of program'Anna'
💡 Program ends after greet method returns the greeting string.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
@namenil'Anna''Anna''Anna'
Key Moments - 2 Insights
Why do we use @ before the variable name?
The @ sign marks the variable as an instance variable, meaning it belongs to the object and keeps its value between method calls, as shown in step 1 and 2 of the execution_table.
Can instance variables be accessed outside the object directly?
No, instance variables are private to the object. You access them through methods like greet(), as seen in step 2 where @name is used inside the method.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of @name after creating the Person object?
A"Hello, Anna!"
Bnil
C'Anna'
Dundefined
💡 Hint
Check Step 1 in execution_table where @name changes from nil to 'Anna'.
At which step does the greet method use the instance variable @name?
AStep 1
BStep 2
CStep 3
DNone
💡 Hint
Look at Step 2 in execution_table where greet method is called and @name is used.
If we create another Person object with name 'Bob', what will @name be for that object?
A'Bob'
B'Anna'
Cnil
Dshared between objects
💡 Hint
Instance variables are unique to each object, as shown by @name holding 'Anna' for the first object.
Concept Snapshot
Instance variables start with @ and belong to an object.
They store data unique to that object.
Set them in initialize or other methods.
Access them inside methods with @name.
Each object has its own copy.
They are private to the object.
Full Transcript
In Ruby, instance variables start with @ and belong to each object created from a class. When you create an object, you can set instance variables to store data unique to that object. For example, in the Person class, @name stores the person's name. Methods inside the class can use these variables to work with the object's data. Instance variables keep their values as long as the object exists. They cannot be accessed directly from outside the object but only through methods. This helps keep data safe and organized per object.

Practice

(1/5)
1. What does an instance variable in Ruby always start with?
easy
A. An at symbol (@)
B. A dollar sign ($)
C. A hash symbol (#)
D. A percent sign (%)

Solution

  1. Step 1: Recall Ruby instance variable syntax

    Instance variables in Ruby always begin with the at symbol (@) to distinguish them from local variables.
  2. Step 2: Identify the correct symbol

    Among the options, only the at symbol (@) is used to start instance variables.
  3. Final Answer:

    An at symbol (@) -> Option A
  4. Quick Check:

    Instance variable starts with @ [OK]
Hint: Instance variables always start with @ in Ruby [OK]
Common Mistakes:
  • Confusing instance variables with global variables ($)
  • Using local variable syntax without @
  • Thinking instance variables start with # or %
2. Which of the following is the correct way to define an instance variable inside a Ruby class?
easy
A. var @name = 'Alice'
B. @name = 'Alice'
C. name = @'Alice'
D. def @name = 'Alice'

Solution

  1. Step 1: Understand instance variable assignment syntax

    In Ruby, instance variables are assigned by writing @variable_name = value inside methods or constructors.
  2. Step 2: Check each option

    @name = 'Alice' correctly assigns an instance variable. The other options use invalid syntax.
  3. Final Answer:

    @name = 'Alice' -> Option B
  4. Quick Check:

    Assign instance variable with @name = value [OK]
Hint: Assign instance variables with @name = value inside methods [OK]
Common Mistakes:
  • Adding var keyword (not used in Ruby)
  • Placing @ inside quotes
  • Using def keyword incorrectly
3. What will be the output of this Ruby code?
class Person
  def initialize(name)
    @name = name
  end
  def greet
    "Hello, #{@name}!"
  end
end

p = Person.new('Bob')
puts p.greet
medium
A. Error: undefined variable
B. Hello, @name!
C. Hello, name!
D. Hello, Bob!

Solution

  1. Step 1: Understand instance variable assignment in initialize

    The initialize method sets @name to 'Bob' when Person.new('Bob') is called.
  2. Step 2: Evaluate greet method output

    The greet method returns a string with #{@name} replaced by the instance variable value 'Bob'.
  3. Final Answer:

    Hello, Bob! -> Option D
  4. Quick Check:

    Instance variable @name holds 'Bob' so output is Hello, Bob! [OK]
Hint: Instance variables keep data per object, used inside methods with @ [OK]
Common Mistakes:
  • Expecting literal '@name' in output
  • Confusing local and instance variables
  • Forgetting to use @ in string interpolation
4. Identify the error in this Ruby class code:
class Car
  def initialize(model)
    name = model
  end
  def show
    puts @name
  end
end

car = Car.new('Tesla')
car.show
medium
A. Syntax error in initialize method
B. Method show is missing return statement
C. Instance variable @name is not assigned, so nil is printed
D. Cannot call puts inside method

Solution

  1. Step 1: Check variable assignment in initialize

    The code assigns local variable name = model, not instance variable @name.
  2. Step 2: Understand effect on show method

    Since @name is never set, @name is nil, so puts prints an empty line (nil).
  3. Final Answer:

    Instance variable @name is not assigned, so nil is printed -> Option C
  4. Quick Check:

    Local variable assigned, not instance variable @name [OK]
Hint: Use @ to assign instance variables, not plain variable names [OK]
Common Mistakes:
  • Assigning local variable instead of instance variable
  • Expecting puts to fail without return
  • Thinking syntax error occurs here
5. You want to create a Ruby class Book that stores a title and author as instance variables. You also want a method description that returns "Title by Author". Which code correctly implements this?
hard
A. class Book def initialize(title, author) @title = title @author = author end def description "#{@title} by #{@author}" end end
B. class Book def initialize(title, author) title = @title author = @author end def description "#{title} by #{author}" end end
C. class Book def initialize(title, author) @title = title @author = author end def description "title by author" end end
D. class Book def initialize(title, author) @title = title @author = author end def description "#{title} by #{author}" end end

Solution

  1. Step 1: Assign instance variables correctly in initialize

    class Book def initialize(title, author) @title = title @author = author end def description "#{@title} by #{@author}" end end assigns @title and @author from parameters correctly. class Book def initialize(title, author) title = @title author = @author end def description "#{title} by #{author}" end end reverses assignment. The remaining options misuse variables in description.
  2. Step 2: Use instance variables in description method

    class Book def initialize(title, author) @title = title @author = author end def description "#{@title} by #{@author}" end end uses #{@title} and #{@author} inside string interpolation, correctly accessing instance variables.
  3. Final Answer:

    class Book def initialize(title, author) @title = title @author = author end def description "#{@title} by #{@author}" end end -> Option A
  4. Quick Check:

    Assign and use @variables inside methods for correct output [OK]
Hint: Assign and use instance variables with @ inside all methods [OK]
Common Mistakes:
  • Assigning variables backwards (param = @var)
  • Using local variables instead of instance variables in methods
  • Returning literal strings without interpolation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard