What are getter and setter methods in Ruby?

Getter and Setter methods are used to get and set the values of instance variables respectively. Without gettter methods you can not read the values of instance variables of an instance and without setter methods you can not set/update the values of instance variables of an instance.

Conside the following example to understand that how to implement the getter and setter methods:

            
              class Rectangle
                def initialize(length, width)
                  @length = length
                  @width = width
                  return @length
                end

                def length # getter method to read the value of @length
                  @length
                end

                def width # getter method to read the value of @width
                  @width
                end

                def length=(value) # setter method to update the value of @length
                  @length = value
                end

                def width=(value) # setter method to update the value of @width
                  @width = value
                end

                def area
                  @length * @width
                end

                def peremeter
                  2 * (@length + @width)
                end
              end

              @rectangle = Rectangle.new(100, 200)
              # <Rectangle:0x000000012f9e3ab0 @length=100, @width=200>

              @rectangle.length
              # 100

              @rectangle.length = 120

              @rectangle.length
              # 120
            
          

Here you need to notice one thing that the getter and setter methods must have their name same as the name of instance variables.

APPSIMPACT Academy

Ruby on Rails is a very popular and most productive web application development framework. At APPSIMPACT Academy we provide best content to learn Ruby on Rails framework.

Questions & Answers
What is the difference between instance variables and local variables? What is initialize() method in Ruby? What are getter and setter methods in Ruby? Comparision between rails 4, 5 and 6 What is difference between sub and gsub in Ruby? How to recreate flatten method in Ruby using recursion?