ruby attr_reader attr_writer attr_accessor
In Ruby, we can use attr_reader to give object instances a simpler way to read the class instance variables:
class TeaMaker
attr_reader :colour, :temperature, :quantity, :origin, :brand
def initialize(colour,temperature, quantity, origin, brand)
@colour = colour
@temperature = temperature
@quantity = quantity
@origin = origin
@brand = brand
end
end
teat1 = TeaMaker.new("dark", "hot", "small", "China", "puer")
puts tea1.colour // dark
puts tea1.temperature //hot
puts tea1.quantity // small
puts tea1.origin // China
puts tea1.brand // puer
Now imagine, that the TeaMaker has not one but five instance variables. For this to work, we’ll have to create 5 methods to provide access to read them and 5 methods to change their respective values. This can quickly become difficult to manage.
In Ruby, we can use attr_writer along with attr_reader to give object instances a simpler way to update the class instance variables:
class TeaMaker
attr_reader :colour, :temperature, :quantity, :origin, :brand
attr_writer :colour, :temperature, :quantity, :origin, :brand
def initialize(colour, temperature, quantity, origin, brand)
@colour = colour
@temperature = temperature
@quantity = quantity
@origin = origin
@brand = brand
end
end
tea1 = TeaMaker.new("dark", "hot", "small", "Brunei", "Domos")
tea1.colour = "light"
puts tea1.colour
tea1.temperature = "cold"
puts tea1.temperature
tea1.quantity = "large"
puts tea1.quantity
tea1.origin = "nochina"
puts tea1.origin
tea1.brand = "longjin"
puts tea1.brand
attr_reader :colour, :temperature, :quantity, :origin, :brand attr_writer :colour, :temperature, :quantity, :origin, :brand it seems like a complicated way to achieve a simple thing: access and change instance variables. Ruby provides us with attr_accessor to simplify this code:
class TeaMaker
attr_accessor :colour, :temperature, :quantity, :origin, :brand
def initialize(colour, temperature, quantity, origin, brand)
@colour = colour
@temperature = temperature
@quantity = quantity
@origin = origin
@brand = brand
end
end
tea1 = TeaMaker.new("dark", "hot", "small", "Brunei", "Domos")
tea1.colour = "light"
puts tea1.colour
tea1.temperature = "cold"
puts tea1.temperature
tea1.quantity = "large"
puts tea1.quantity
tea1.origin = "nochina"
puts tea1.origin
tea1.brand = "longjin"
puts tea1.brand