Ruby Accessors
An accessor is a method that lets outside code read or change a value stored inside an object. The attr lines write accessor methods for a class.
A stored name stays hidden
The dog stores its name in @name. respond_to? asks if the object answers to name, and it prints false because no reader exists yet.
class Dog
def initialize(name)
@name = name
end
end
dog = Dog.new("Rex")
puts dog.respond_to?(:name)A hand-written reader
The name method inside the class gives @name to outside code. respond_to? prints true now, and the name itself prints.
class Dog
def initialize(name)
@name = name
end
def name
@name
end
end
dog = Dog.new("Rex")
puts dog.respond_to?(:name)
puts dog.nameattr_reader writes the reader
attr_reader :name writes the same reader method for the class. The two printed lines match the hand-written version.
class Dog
attr_reader :name
def initialize(name)
@name = name
end
end
dog = Dog.new("Rex")
puts dog.respond_to?(:name)
puts dog.nameattr_writer sets a new name
attr_writer :name writes a method that sets @name from outside. The greet line shows the new name after the change.
class Dog
attr_writer :name
def initialize(name)
@name = name
end
def greet
puts "#{@name} says hello"
end
end
dog = Dog.new("Rex")
dog.name = "Max"
dog.greetattr_accessor does both jobs
attr_accessor :name writes the reader and the writer in one line. The name prints, changes, and prints again.
class Dog
attr_accessor :name
def initialize(name)
@name = name
end
end
dog = Dog.new("Rex")
puts dog.name
dog.name = "Max"
puts dog.nameExample
class Dog
attr_accessor :name
attr_accessor :age
def initialize(name, age)
@name = name
@age = age
end
def profile
puts "#{@name} is #{@age} years old"
end
end
dog = Dog.new("Rex", 3)
puts dog.name
dog.age = 4
dog.profileKey points
- A value in @name stays hidden from outside code until a method shares it.
- A reader is a method that gives outside code a stored value.
- attr_reader writes a reader method for the named value.
- attr_writer writes a writer method for the named value.
- attr_accessor writes both a reader and a writer.
- A writer call looks like a plain assignment, as in dog.name = "Max".
In this example, attr_accessor lines give Dog a reader and a writer for name and age. The first print reads the name through the reader. Setting age to 4 uses the writer, and profile shows the new age.
Note
The name after an attr word is a symbol, like :name.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
Which line writes both a reader and a writer for name?