Consider this Ruby class with attr_reader. What will be printed?
class Person attr_reader :name def initialize(name) @name = name end end p = Person.new("Alice") puts p.name p.name = "Bob"
Remember, attr_reader creates a getter method but no setter.
attr_reader creates a method to read the instance variable but does not allow writing. So p.name works and prints "Alice". But p.name = "Bob" raises a NoMethodError because the setter method is missing.
Look at this Ruby code using attr_writer. What will be the output or error?
class Car attr_writer :color def initialize(color) @color = color end end car = Car.new("red") puts car.color car.color = "blue" puts car.instance_variable_get(:@color)
attr_writer creates a setter but no getter method.
attr_writer creates a setter method color= but no getter color. So car.color raises NoMethodError. The setter car.color = "blue" works and changes the instance variable. Using instance_variable_get shows the updated value.
Given this Ruby class with attr_accessor, what will be printed?
class Book attr_accessor :title def initialize(title) @title = title end end book = Book.new("Ruby 101") puts book.title book.title = "Ruby 102" puts book.title
attr_accessor creates both getter and setter methods.
attr_accessor creates both title and title= methods. So you can read and write the @title instance variable. The output shows the original title and the updated title.
Choose the correct statement about these Ruby attribute methods.
Think about which methods allow reading and writing.
attr_reader creates only getter methods. attr_writer creates only setter methods. attr_accessor creates both getter and setter methods.
Look at this code snippet. Why does puts user.name raise NoMethodError?
class User attr_writer :name def initialize(name) @name = name end end user = User.new("Eve") puts user.name
Check what methods attr_writer creates.
attr_writer creates only the setter method name=. It does not create a getter method name. So calling user.name raises NoMethodError.