author avatar

syedsibtain

Tue Nov 19 2024

In Ruby, attr_reader and attr_accessor are used to create getter and setter methods for class attributes. These are part of a group of methods (attr_* methods) that make it easier to create getter and setter methods for class attributes.

attr_reader: Creates a getter method, allowing read-only access to an instance variable.


class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

person = Person.new("Sibtain")
puts person.name  # Outputs: Sibtain


attr_accessor: Creates both getter and setter methods, allowing read and write access to an instance variable.


class Person
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

person = Person.new("Sibtain")
puts person.name  # Outputs: Sibtain

person.name = "John"
puts person.name  # Outputs: John


Furthermore, using attr_reader and attr_accessor promotes encapsulation by controlling how the attributes of a class are accessed and modified.

#ruby #rubyonrails