Start Coding

Topics

Ruby Getters and Setters

In Ruby, getters and setters are methods that allow controlled access to an object's attributes. They're fundamental to Ruby Encapsulation, providing a way to read and modify an object's state.

What are Getters?

Getters are methods that retrieve the value of an instance variable. They're also known as accessor methods.

Basic Getter Syntax


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

  def name
    @name
  end
end

person = Person.new("Alice")
puts person.name  # Output: Alice
    

What are Setters?

Setters, also called mutator methods, allow you to change the value of an instance variable.

Basic Setter Syntax


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

person = Person.new("Bob")
person.name = "Charlie"
puts person.name  # Output: Charlie
    

Combining Getters and Setters

Often, you'll want both getter and setter methods for an attribute. Here's how to implement both:


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

  def name
    @name
  end

  def name=(new_name)
    @name = new_name
  end
end

person = Person.new("David")
puts person.name        # Output: David
person.name = "Eve"
puts person.name        # Output: Eve
    

Shortcut: attr_accessor

Ruby provides a shortcut for creating both getter and setter methods using attr_* Methods:


class Person
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

person = Person.new("Frank")
puts person.name        # Output: Frank
person.name = "Grace"
puts person.name        # Output: Grace
    

Best Practices

  • Use getters and setters instead of directly accessing instance variables.
  • Implement custom logic in getters and setters when necessary (e.g., validation).
  • Consider using attr_reader for read-only attributes.
  • Use attr_writer for write-only attributes (rare, but possible).

When to Use Custom Getters and Setters

While attr_accessor is convenient, custom getters and setters are useful for:

  • Adding validation logic
  • Formatting data
  • Implementing computed properties
  • Logging access or changes

Example: Custom Setter with Validation


class Person
  attr_reader :age

  def age=(new_age)
    if new_age >= 0 && new_age <= 120
      @age = new_age
    else
      raise ArgumentError, "Age must be between 0 and 120"
    end
  end
end

person = Person.new
person.age = 30  # Valid
person.age = 150 # Raises ArgumentError
    

By mastering getters and setters, you'll enhance your ability to create robust and maintainable Ruby Ruby Classes and Ruby Objects.