Instance variables (@) in Ruby - Time & Space Complexity
Let's see how using instance variables affects the time it takes for a program to run.
We want to know if accessing or setting instance variables changes how long the program takes as it runs.
Analyze the time complexity of the following code snippet.
class Person
def initialize(name)
@name = name
end
def greet
"Hello, #{@name}!"
end
end
person = Person.new("Alice")
puts person.greet
This code creates a person with a name stored in an instance variable and then greets using that name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the instance variable
@nameinside thegreetmethod. - How many times: Each time
greetis called, the instance variable is accessed once.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 accesses to @name if greet called 10 times |
| 100 | 100 accesses to @name if greet called 100 times |
| 1000 | 1000 accesses to @name if greet called 1000 times |
Pattern observation: The time grows directly with how many times you call the method that uses the instance variable.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of times you call the method that accesses the instance variable.
[X] Wrong: "Accessing an instance variable is slow and adds extra loops behind the scenes."
[OK] Correct: Accessing an instance variable is a simple, direct operation that takes the same time each time, not a loop or repeated search.
Understanding how instance variables work helps you explain how your code stores and accesses data efficiently, a key skill in programming.
"What if we changed the instance variable to a class variable? How would the time complexity change when accessing it multiple times?"
Practice
Solution
Step 1: Recall Ruby instance variable syntax
Instance variables in Ruby always begin with the at symbol (@) to distinguish them from local variables.Step 2: Identify the correct symbol
Among the options, only the at symbol (@) is used to start instance variables.Final Answer:
An at symbol (@) -> Option AQuick Check:
Instance variable starts with @ [OK]
- Confusing instance variables with global variables ($)
- Using local variable syntax without @
- Thinking instance variables start with # or %
Solution
Step 1: Understand instance variable assignment syntax
In Ruby, instance variables are assigned by writing @variable_name = value inside methods or constructors.Step 2: Check each option
@name = 'Alice' correctly assigns an instance variable. The other options use invalid syntax.Final Answer:
@name = 'Alice' -> Option BQuick Check:
Assign instance variable with @name = value [OK]
- Adding var keyword (not used in Ruby)
- Placing @ inside quotes
- Using def keyword incorrectly
class Person
def initialize(name)
@name = name
end
def greet
"Hello, #{@name}!"
end
end
p = Person.new('Bob')
puts p.greetSolution
Step 1: Understand instance variable assignment in initialize
The initialize method sets @name to 'Bob' when Person.new('Bob') is called.Step 2: Evaluate greet method output
The greet method returns a string with #{@name} replaced by the instance variable value 'Bob'.Final Answer:
Hello, Bob! -> Option DQuick Check:
Instance variable @name holds 'Bob' so output is Hello, Bob! [OK]
- Expecting literal '@name' in output
- Confusing local and instance variables
- Forgetting to use @ in string interpolation
class Car
def initialize(model)
name = model
end
def show
puts @name
end
end
car = Car.new('Tesla')
car.showSolution
Step 1: Check variable assignment in initialize
The code assigns local variable name = model, not instance variable @name.Step 2: Understand effect on show method
Since @name is never set, @name is nil, so puts prints an empty line (nil).Final Answer:
Instance variable @name is not assigned, so nil is printed -> Option CQuick Check:
Local variable assigned, not instance variable @name [OK]
- Assigning local variable instead of instance variable
- Expecting puts to fail without return
- Thinking syntax error occurs here
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?Solution
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.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.Final Answer:
class Book def initialize(title, author) @title = title @author = author end def description "#{@title} by #{@author}" end end -> Option AQuick Check:
Assign and use @variables inside methods for correct output [OK]
- Assigning variables backwards (param = @var)
- Using local variables instead of instance variables in methods
- Returning literal strings without interpolation
Ready to prove it?
Pass the test and this pattern moves unknown
