How to use Getters and Setters in Ruby

Image for post
Image for post
Photo by Caspar Camille Rubin on Unsplash

Getter and Setter methods in Ruby are gateways to access class instance variables. In this blog post I will explain how to create a class with getter and setter methods.

Let’s explain what a getter and a setter method in Ruby are!

A Getter method is the only way where you can retrieve the value of an instance variable from outside its class. A Setter method is the only way where you can assign a value to an instance variable from outside its class.

Now that we have an idea on what each one is, let’s explain them using an example.

Here is a Student class:

We defined a Student class and then later on we created a student giving her the name “Sarah”, however when we tried to access the student name, it gave us a because it is trying to look for a method called name but we never defined this method.

As we said before, we need to define a getter method to be able to retrieve the student name:

Here we were able to retrieve the name because we defined a getter method for the name instance variable.

Now, let’s try to change the name of the student:

Here when we tried to assign another name to the student, we got a because we never defined a setter method for the name instance variable.

Here is how we define a setter method:

Notice how we defined the setter method adding to the end of its name to indicate it is a setter method. When we do this will automatically call the setter method sending whatever is after the equal sign to the method as a parameter.

Hope that gave you a clear explanation on Getters and Setters in Ruby. If you would like to add anything, please comment below!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store