There are several getter and setter commentary articles, so I'll leave that to you. Also, there is a convenient code called Accessor, but I didn't have enough information about how to use it properly, so I wrote it as a basis for beginners.
First of all, it is a place to design a common car.
Car design
class Car
attr_accessor :model, :color, :option
def initialize(model, color, option)
@model = model
@color = color
@option = option
end
end
car = Car.new("Benz", "white", "wheel")
#=>All can be changed
If this is the case, you can put it together with attr_accessor
,
For example, ** "I'm already making a car, but I'm in trouble if I can change the color with the car model !!! (I wish it was only an option ...)" **
Car design
class Car
attr_reader :model, :color, :option
attr_writer :option
def initialize(model, color, option)
@model = model
@color = color
@option = option
end
end
car = Car.new("Benz", "white", "wheel")
#=>Only options can be changed
It's common to write that, If you want to write smarter with accessors
Car design
class Car
attr_accessor :option
attr_reader :model, :color
def initialize(model, color, option)
@model = model
@color = color
@option = option
end
end
car = Car.new("Benz", "white", "wheel")
#=>Only options can be changed
Will be.
By the way,
Car design
class Car
attr_accessor :option
attr_reader :model, :color
def initialize(model, color, option)
@model = model
@color = color
@option = option
end
end
car = Car.new("Benz", "white", "wheel")
car.model = "BMW"
#=>NoMethodError (undefined method `model=' for #<Car:0x00007fc009900440>)
I get angry like that! !! ** "Don't change the car model! I'm already making it!" ** That's right. Attempting to change the color will result in a similar error.
So, I looked back on how to use getters, setters, and accessors for Ruby beginners to study. I hope it will be helpful for beginners. Thank you very much! !!
Recommended Posts