Attr_reader, attr_writer, attr_accessor in Ruby - Time & Space Complexity
Let's see how using attr_reader, attr_writer, and attr_accessor affects the speed of our Ruby code.
We want to know how the time to access or change object properties grows as we use these shortcuts.
Analyze the time complexity of the following Ruby class using these attribute helpers.
class Person
attr_accessor :name
attr_reader :age
attr_writer :email
def initialize(name, age, email)
@name = name
@age = age
@email = email
end
end
person = Person.new("Alice", 30, "alice@example.com")
person.name = "Bob"
puts person.age
person.email = "bob@example.com"
This code defines a class with automatic getter and setter methods for its properties.
Look for operations that happen multiple times or grow with input.
- Primary operation: Accessing or setting instance variables via generated methods.
- How many times: Each access or set is a single direct operation, no loops or recursion.
Each time you get or set a property, it takes the same small amount of time, no matter how many properties or objects you have.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 simple property accesses or sets |
| 100 | 100 simple property accesses or sets |
| 1000 | 1000 simple property accesses or sets |
Pattern observation: The time grows directly with how many times you access or set properties, but each is quick and does not depend on other factors.
Time Complexity: O(1)
This means each property access or change takes the same small amount of time, no matter how many objects or properties exist.
[X] Wrong: "Using attr_accessor makes property access slower because it adds extra code."
[OK] Correct: These helpers just create simple methods that run very fast, so they do not slow down your program noticeably.
Understanding how these shortcuts work and their speed helps you write clean and efficient Ruby code, a skill useful in many coding situations.
"What if we replaced attr_accessor with manual getter and setter methods? How would the time complexity change?"
Practice
attr_reader do in a Ruby class?Solution
Step 1: Understand attr_reader purpose
attr_readerdefines a getter method for an instance variable, allowing you to read its value.Step 2: Compare with other attr methods
attr_writercreates a setter (write) method, andattr_accessorcreates both getter and setter methods.Final Answer:
Creates a method to read an attribute value -> Option AQuick Check:
attr_reader = read method [OK]
- Confusing attr_reader with attr_writer
- Thinking attr_reader allows writing values
- Mixing attr_accessor with attr_reader
@name in Ruby?Solution
Step 1: Recall attr_accessor usage
attr_accessorcreates both getter and setter methods for the given symbol.Step 2: Check other options
attr_readeronly creates getter,attr_writeronly setter, andattr_bothis invalid syntax.Final Answer:
attr_accessor :name -> Option BQuick Check:
attr_accessor = read + write [OK]
- Using attr_reader when write is needed
- Using invalid method names like attr_both
- Confusing attr_writer with attr_accessor
class Person
attr_writer :age
def initialize(age)
@age = age
end
def show_age
@age
end
end
p = Person.new(30)
puts p.show_age
p.age = 40
puts p.show_ageSolution
Step 1: Understand attr_writer effect
attr_writer :agecreates a setter methodage=, but no getter method is created.Step 2: Analyze method calls
p.show_agereturns@agewhich is 30 initially. Thenp.age = 40sets@ageto 40. Butp.show_agereturns@agewhich is now 40.Step 3: Check output
Actually,p.show_ageis called twice, before and after setting age. So outputs are 30 then 40.Final Answer:
30\n40 -> Option AQuick Check:
attr_writer allows setting, show_age reads @age [OK]
- Assuming attr_writer creates getter method
- Expecting error on p.age= assignment
- Confusing show_age method with attr_reader
class Car
attr_reader :model
def initialize(model)
@model = model
end
def model=(value)
@model = value
end
end
car = Car.new('Sedan')
car.model = 'SUV'
puts car.modelSolution
Step 1: Check attr_reader and setter method
attr_reader :modelcreates a getter method. The setter methodmodel=is manually defined.Step 2: Analyze method calls
car.model = 'SUV'calls the manual setter, updating@model.puts car.modelcalls the getter from attr_reader, printing 'SUV'.Final Answer:
No error, code runs and prints 'SUV' -> Option DQuick Check:
attr_reader + manual setter works [OK]
- Assuming attr_reader creates setter method
- Thinking attr_reader conflicts with manual setter
- Expecting error on model= assignment
Book where the title can be read but not changed, and the author can be both read and changed. Which attribute methods should you use?Solution
Step 1: Determine access for title
Title should be readable but not writable, so useattr_reader :title.Step 2: Determine access for author
Author should be readable and writable, so useattr_accessor :author.Final Answer:
attr_reader :title attr_accessor :author -> Option CQuick Check:
Read-only + read-write = attr_reader + attr_accessor [OK]
- Using attr_writer for read-only attribute
- Using attr_accessor for read-only attribute
- Mixing up read and write access
Ready to prove it?
Pass the test and this pattern moves unknown
