Ruby getters and setters Method
Last Updated :
11 Oct, 2019
In a Ruby class we may want to expose the instance variables (the variables that are defined prefixed by @ symbol) to other classes for encapsulation. Then, in that case, we use the
getter and setter methods. these methods allow us to access a class's instance variable from outside the class. Getter methods are used to
get the value of an instance variable while the setter methods are used to
set the value of an instance variable of some class.
Example 1: Simple get method
Ruby
# Ruby Program of getter method
class CSWebsite
# Constructor to initialize
# the class with a name
# instance variable
def initialize(website)
@website = website
end
# Classical get method
def website
@website
end
end
# Creating an object of the class
gfg = CSWebsite.new "www.geeksforgeeks.org"
puts gfg.website
Output :
www.geeksforgeeks.org
In this example, if we don't define the
website method in the class, the puts statement used later (gfg.website) would give us an exception because the @
website variable is the class's instance variable and it should not be accessible outside the class by default.
Example 2: Simple set method
Ruby
# Ruby Program of setter method
class CSWebsite
# Constructor to initialize
# the class with a name
# instance variable
def initialize(website)
@website = website
end
# Classical get method
def website
@website
end
# Classical set method
def website=(website)
@website = website
end
end
# Creating an object of the class
gfg = CSWebsite.new "www.geeksforgeeks.org"
puts gfg.website
# Change the instance variable from
# Outside the class
gfg.website="www.practice.geeksforgeeks.org"
puts gfg.website
Output :
www.geeksforgeeks.org
www.practice.geeksforgeeks.org
In this example, if we don't define the
website= method in the class, then we can't change the value of the class's instance variable. With the help of this setter method, we reused the same object for multiple websites.
In the above examples, we can be seen that as the class grows we might have many getter and setter methods most of which follow the same format as shown above. To fix these growing lines of code, Ruby provides us with a quick way to generate the getter and setter methods without explicitly writing them as we did in the above examples. These methods are known as
accessor methods. Their purpose is the same as that of a getter or setter.
There are
three types of accessors in Ruby
- attr_reader : This accessor generates the automatic Getter method for the given item.
- attr_writer : This accessor generates the automatic Setter method for the given item.
- attr_accessor : This accessor generates the automatic Getter & Setter method for the given item.