An attribute accessor in Ruby is a way of declaring attribute accessibility (read and write) via Ruby's metaprogramming facilities.
Usage
Given any Ruby class, one can use the attr_accessor
method like so:
class Car
attr_accessor :speed
end
This enables us to read and write the speed
instance variable of any instance of Car
:
my_car = Car.new
my.car.speed = 100
my.car.speed # => 100
The attr_accessor
method implements this functionality by creating new methods for the class it was called in.
Internals
Therefore, using attr_accessor
is actually equivalent to the following:
class Car
attr_reader :speed
attr_writer :speed
end
which in turn is the same as
class Car
def speed
@speed
end
def speed=(v)
@speed = v
end
end