Bird
Raised Fist0
Rubyprogramming~10 mins

Attr_reader, attr_writer, attr_accessor in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Attr_reader, attr_writer, attr_accessor
Define class with attr_*
↓
Create object instance
↓
Access or modify attribute
↓
attr_reader
↓
Read value
↓
attr_accessor
↓
Read and write value
This flow shows how Ruby's attr_reader, attr_writer, and attr_accessor create methods to read, write, or both read and write object attributes.
Execution Sample
Ruby
class Person
  attr_reader :name
  attr_writer :age
  attr_accessor :city
end

p = Person.new
p.city = "NY"
Defines a Person class with different attribute accessors and sets the city attribute.
Execution Table
StepActionAttributeMethod CreatedOperationResult/Value
1Define attr_reader :namenamedef name; @name; endReadMethod to get @name created
2Define attr_writer :ageagedef age=(val); @age = val; endWriteMethod to set @age created
3Define attr_accessor :citycitydef city; @city; end and def city=(val); @city = val; endRead & WriteMethods to get and set @city created
4Create Person instance---Object p created
5Set p.city = "NY"citycity= method calledWrite@city set to "NY"
6Try to read p.namenamename method calledReadReturns nil (not set)
7Try to set p.age = 30ageage= method calledWrite@age set to 30
8Try to read p.ageageNo method createdReadError: undefined method 'age'
9Try to read p.citycitycity method calledReadReturns "NY"
💡 Execution stops after demonstrating read/write methods created and used for attributes.
Variable Tracker
VariableStartAfter Step 5After Step 7After Step 9
@namenilnilnilnil
@agenilnil3030
@citynil"NY""NY""NY"
Key Moments - 3 Insights
Why can we read p.name but not p.age?
Because attr_reader creates a method to read @name (see step 1 and 6), but attr_writer only creates a method to write @age (step 2 and 7). There is no method to read @age, so reading it causes an error (step 8).
What does attr_accessor do differently?
attr_accessor creates both read and write methods for the attribute (step 3). So for :city, we can both read and write its value (steps 5 and 9).
Why does p.city return "NY" after setting it?
Because attr_accessor created a getter method that returns the current value of @city, which was set to "NY" in step 5 and read in step 9.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens when we try to read p.age at step 8?
AIt returns the value 30
BIt causes an error because no read method exists
CIt returns nil
DIt sets @age to 30
💡 Hint
Check step 8 in the execution_table where reading p.age fails due to missing method.
At which step is the write method for :city created?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at step 3 where attr_accessor creates both read and write methods for city.
If we add attr_reader :age, what would change in the execution table?
AStep 5 would fail to set city
BStep 7 would cause an error
CStep 8 would return 30 instead of error
DNo change at all
💡 Hint
Adding attr_reader :age creates a read method, so reading p.age at step 8 would succeed.
Concept Snapshot
attr_reader :symbol  # creates getter method to read attribute
attr_writer :symbol  # creates setter method to write attribute
attr_accessor :symbol # creates both getter and setter
Use to avoid writing simple methods manually.
attr_reader allows reading only, attr_writer writing only, attr_accessor both.
Full Transcript
This visual execution shows how Ruby's attr_reader, attr_writer, and attr_accessor work. First, attr_reader creates a method to read an attribute's value. attr_writer creates a method to write or change the attribute's value. attr_accessor creates both read and write methods. We define a Person class with these attributes. When we create an instance and try to read or write attributes, only the methods created by attr_* work. For example, reading p.name works because of attr_reader, but reading p.age fails because only attr_writer was defined. Setting and reading p.city works because attr_accessor was used. This helps avoid writing simple getter and setter methods manually.

Practice

(1/5)
1. What does attr_reader do in a Ruby class?
easy
A. Creates a method to read an attribute value
B. Creates a method to write an attribute value
C. Creates methods to both read and write an attribute
D. Deletes an attribute from the class

Solution

  1. Step 1: Understand attr_reader purpose

    attr_reader defines a getter method for an instance variable, allowing you to read its value.
  2. Step 2: Compare with other attr methods

    attr_writer creates a setter (write) method, and attr_accessor creates both getter and setter methods.
  3. Final Answer:

    Creates a method to read an attribute value -> Option A
  4. Quick Check:

    attr_reader = read method [OK]
Hint: attr_reader = read only method [OK]
Common Mistakes:
  • Confusing attr_reader with attr_writer
  • Thinking attr_reader allows writing values
  • Mixing attr_accessor with attr_reader
2. Which of the following is the correct syntax to create both getter and setter methods for @name in Ruby?
easy
A. attr_writer :name
B. attr_accessor :name
C. attr_reader :name
D. attr_both :name

Solution

  1. Step 1: Recall attr_accessor usage

    attr_accessor creates both getter and setter methods for the given symbol.
  2. Step 2: Check other options

    attr_reader only creates getter, attr_writer only setter, and attr_both is invalid syntax.
  3. Final Answer:

    attr_accessor :name -> Option B
  4. Quick Check:

    attr_accessor = read + write [OK]
Hint: Use attr_accessor for read and write [OK]
Common Mistakes:
  • Using attr_reader when write is needed
  • Using invalid method names like attr_both
  • Confusing attr_writer with attr_accessor
3. What will be the output of this Ruby code?
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_age
medium
A. 30\n40
B. 30\n30
C. Error: undefined method `age='
D. Error: undefined method `show_age'

Solution

  1. Step 1: Understand attr_writer effect

    attr_writer :age creates a setter method age=, but no getter method is created.
  2. Step 2: Analyze method calls

    p.show_age returns @age which is 30 initially. Then p.age = 40 sets @age to 40. But p.show_age returns @age which is now 40.
  3. Step 3: Check output

    Actually, p.show_age is called twice, before and after setting age. So outputs are 30 then 40.
  4. Final Answer:

    30\n40 -> Option A
  5. Quick Check:

    attr_writer allows setting, show_age reads @age [OK]
Hint: attr_writer only sets; custom getter needed [OK]
Common Mistakes:
  • Assuming attr_writer creates getter method
  • Expecting error on p.age= assignment
  • Confusing show_age method with attr_reader
4. Identify the error in this Ruby class:
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.model
medium
A. Error: attr_reader conflicts with manual setter method
B. Error: undefined method 'model='
C. Error: attr_reader does not create setter method
D. No error, code runs and prints 'SUV'

Solution

  1. Step 1: Check attr_reader and setter method

    attr_reader :model creates a getter method. The setter method model= is manually defined.
  2. Step 2: Analyze method calls

    car.model = 'SUV' calls the manual setter, updating @model. puts car.model calls the getter from attr_reader, printing 'SUV'.
  3. Final Answer:

    No error, code runs and prints 'SUV' -> Option D
  4. Quick Check:

    attr_reader + manual setter works [OK]
Hint: attr_reader + manual setter is valid [OK]
Common Mistakes:
  • Assuming attr_reader creates setter method
  • Thinking attr_reader conflicts with manual setter
  • Expecting error on model= assignment
5. You want a Ruby class 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?
hard
A. attr_writer :title attr_writer :author
B. attr_writer :title attr_reader :author
C. attr_reader :title attr_accessor :author
D. attr_accessor :title attr_writer :author

Solution

  1. Step 1: Determine access for title

    Title should be readable but not writable, so use attr_reader :title.
  2. Step 2: Determine access for author

    Author should be readable and writable, so use attr_accessor :author.
  3. Final Answer:

    attr_reader :title attr_accessor :author -> Option C
  4. Quick Check:

    Read-only + read-write = attr_reader + attr_accessor [OK]
Hint: Use attr_reader for read-only, attr_accessor for read-write [OK]
Common Mistakes:
  • Using attr_writer for read-only attribute
  • Using attr_accessor for read-only attribute
  • Mixing up read and write access
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