0
0
Rubyprogramming~10 mins

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

Choose your learning style9 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.