How to Specify Getters and Setters in a Ruby Class?

In a Ruby class, getters/setters can be created for the following:

#Instance Variables

There are two ways in which you can define getters and setters for an instance variable in a Ruby class:

  1. Manually Creating Getters and Setters;
  2. Using Accessors to Auto-Generate Getters and Setters.

Manually Creating Getters and Setters:

You can manually create getters and setters for class instance variables in the following way:

class Person
    def initialize(name)
        @name = name
    end

    def name=(name)
        @name = name
    end

    def name
        @name
    end
end

person = Person.new("John")

puts person.name # output: "John"

person.name = "Bruce"

puts person.name # output: "Bruce"

Using Accessors to Auto-Generate Getters and Setters:

Ruby provides the following accessor methods that automatically generate getter and setter methods for instance variables (negating the need to manually create them):

  1. attr_reader — generates only the getter method;
  2. attr_writer — generates only the setter method;
  3. attr_accessor — generates both, getter and setter methods.

For example, the following would only allow the name and age properties to be read, but not changed:

class Person
    def initialize(name, age)
        @name = name
        @age = age
    end

    attr_reader :name, :age
end

person = Person.new("John", 22)
puts "#{person.name} is #{person.age} years old"

# output: "John is 22 years old"

If you try to set either of the properties it would result in an error:

# ...
person.name = "Bruce"

# undefined method `name=' for #<Person:... @name="John", @age=22> (NoMethodError)

#Class Variables

To create getter/setter methods for class variables, you must create a class method that returns the value of the class variable:

class Foo
    @@bar = "foobar"

    def self.bar
        @@bar
    end
end

puts Foo.bar #=> "foobar"

It is also possible to access a class variable from a class instance by creating a getter instance method.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.