Ruby has many built in shortcuts for allowing access to instance variables. In most languages (Java, PHP ) you typically define your Class properties/variables then would go about defining getter / setter methods for each variable. In Ruby they have defined attribute modifiers to easily define the getter setter methods without having to write them each out.
attr_accessor
The attr_accessor modifier is used to define both getter and setter methods for instance variable(s) of a class.
class Car
attr_accessor :year, :make, :model
end
In the above example we have defined a Car object that has 3 properties year, make, and model. In addition we have made it so that we could read and write to each of those properties.
car = Car.new
car.year = 2010
car.make = "Toyota"
car.model = "Prius"
puts car.year
attr_reader & attr_writer
In some cases you will want to only allow properties to be read or write and not both in those cases you would use attr_reader for read only access and attr_writer for write only access.
class Car
attr_reader :year
attr_writer :owner
end
In this case you would be able to set the @owner property but not read it directly and for @year you would be able to get the property but not set it.
These handy attribute modifiers allow you to quickly define the getter setter methods in your class without taking the time or code to write up each method individually. However be aware that not all properties should be read/writable directly.
Comments & Questions
Add Your Comment