Getters and setters are just methods that are responsible for setting an instance variable (setter), and retrieving the value of an instance variable (getter). Instance variables are only directly accessible to the objects they belong to, which is why those objects need to explicitly provide a way for external code to access them, if that is desired. So written out completely, a getter and setter for the @velocity instance variable of Car would look like this:
- class Car
- def velocity
- @velocity
- end
- def velocity=(new_velocity)
- @velocity = new_velocity
- end
- end
However, Ruby removes the need for this sort of boilerplate:
- class Car
- attr_reader :velocity
- attr_writer :velocity
- end
Or most concisely:
- class Car
- attr_accessor :velocity
- end
All three examples function identically, allowing me to manipulate the velocity instance variable of a car from code outside of the Car class:
- my_car = Car.new
- my_car.velocity = 20 # calls the setter; Ruby's syntactic sugar makes it look like a variable assignment, but it's really a method call to my_car.velocity=(20)
- my_velocity = my_car.velocity # now my_velocity is set to 20, because that's what's returned from the car's getter
32.5K views ·
View upvotes
· 1 of 6 answers
Something went wrong. Wait a moment and try again.