The Attr_accessor, Attr_reader, and Attr_writer in Ruby

Stewart Nguyen Mar 07, 2022
  1. Use the get_data and set_data to Change Data Stored in Instance Variables in Ruby
  2. Use the attr_accessor to Access or Change Data Stored in Instance Variables in Ruby
The Attr_accessor, Attr_reader, and Attr_writer in Ruby

attr_accessor, attr_reader, and attr_writer are used to communicate your intent to the readers and make it easier to write classes.

Use the get_data and set_data to Change Data Stored in Instance Variables in Ruby

We want other classes to access or change data stored in instance variables.

class Foo
  def initialize(data)
    @data = data
  end

  def get_data
    @data
  end

  def set_data(new_data)
    @data = new_data
  end
end

This is a clumsy way for a beginner to get started. Ruby provides a more convenient way to achieve the same result with attr_accessor.

Use the attr_accessor to Access or Change Data Stored in Instance Variables in Ruby

class MyClass
  attr_accessor :data

  def initialize(data)
    @data = data
  end
end

The attr_accessor will define two instance method for MyClass: getter #data and setter #data=

We can use the get_data and set_data methods described above.

my_instance = MyClass.new('private_information')

my_instance.data
=> 'private_information'

my_instance.data = 'information_changed'

puts my_instance.data

Output:

'information_changed'

When we only want a getter method in our class, we can use attr_reader instead of attr_accessor.

Use attr_writter for defining the setter method only.