Mastering Getter and Setter Methods in Ruby: Enhance Your Object-Oriented Programming
- What is a getter method?
- What is a settter method?
In the world of object-oriented programming, mastering getter and setter methods is important to effectively manage the state of objects. Ruby, with its most powerful weapon, elegant syntax, and other powerful features, offers a unique approach to these getter and setter methods. This article deep dives into the topic of getter and setter methods in Ruby.
What is a getter method?
If we need to access a value of a private variable from a class we use a getter method which is commonly known as accessor.
- accessor or getter
What is a settter method?
When we need to change the value of a variable, that is defined inside a class, we use a mutator method commonly known as setter method or writer method.
- mutator or setter or writer
To demonstrate this we will define a class named Car.
Now we make a new instance of the class named Car.
How do we get the values of the instance variables from the car object?
One way is to use the
instance_variable_get method like this
Defining a custom getter method
A much simpler solution is to define a new getter method for each attribute.
now we make a new instance of the class named Car
now we get the instance variable values using getter methods
Using Ruby’s built-in
It is much easier to get the value of the color instance variable with
The best way to make a getter method is to use the built-in Ruby
attr_reader method which automatically creates getter methods for provided attributes
Now we make a new instance of the class named Car
Now we get the instance variable values using attr_reader
To set instance variables inside the car object we can use the
First, define a class named Car
now we make an new instance of the class named Car
to change the values of the color instance variable use
Defining a custom setter method
or we could define a setter method
Let’s display the current values of instance variables
let’s change the color of the car using the setter method
let us check if the color was changed
the color of the car now is Tango instead White
Using Ruby’s built in
Ruby provides the
attr_writer method which provides setter methods for provided attributes, for example
Check if the value was changed
Define getters and setters in the same class
One way using
The easiest way is using the