A Bit About Getter and Setter in Ruby

Daniel Kim
3 min readApr 7, 2021

When working in Ruby, there are many instances where one will need to retrieve or get the value of an instance variable. This can be done with the getter method. Without the getter method, you can not retrieve the value of an instance variable from outside the class it was instantiated from.

Here is an example without a getter method.

Without a getter method, you will end up with an error.

Now with a getter method.

With the getter method, we end up with the desired output.

There will also be moments where one will need to reassign a value to an instance variable. This can be done with the setter method.

Here is an example of trying to reassign a value without the setter method.

This results in a NoMethodError as seen below.

This can be taken care of by using the setter method.

As you can see, with the setter method, we are able to get our desired output.

In Ruby, we are provided an easy way to create getter and setter methods through accessor methods. These are also known as macros.

The three macros in Ruby are attr_reader, attr_writer, and attr_accessor.

The attr_reader is used to create a getter method.

So

Can replace

The attr_writer is used to create a setter method.

So

Can replace

The attr_accessor is used to create both a getter and a setter method.

So

Replaces both

Thus, in this example using the attr_accessor macro, our input and output will be the following.

We can also add multiple instance variables to these macros.

One can see how when working with a class that has many instance variables and requires multiple getter and setter methods, using these accessor methods would be helpful. These methods help one write code as clear and concise as possible, which is always best practice. I hope that this quick simple breakdown and example can be helpful to you on your coding journey.

Thank you for reading!

References

https://www.geeksforgeeks.org/ruby-getters-and-setters-method/

--

--