How to Specify Getters and Setters in a Ruby Class?

Find out how to define getter and setter methods in a Ruby Class

There are two ways in which you can define getters and setters 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 (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 tried 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)

Hope you found this post useful. It was published . Please show your love and support by sharing this post.