DEV Community

Ruslan Khait
Ruslan Khait

Posted on

The attr_accessor in Ruby?

Ruby has object methods by default that are public and also has data that is private. To access and have the able to modify this data, we use the attr_reader and attr_writer.

attr_accessor is a shorter way to have the ability of both attr_reader and attr_writer because people usually use data for both reading and writing. So the method attr_accessor is really quite useful.

Suppose you want to gain access and modify a variable of a Ruby object. Normally, methods would be define separately for reading and writing the data into a variable:

class Person
  def name
    @name
  end

  def name=(str)
    @name = str
  end
end
Enter fullscreen mode Exit fullscreen mode

But, all of the data above could be written in one line using attr_accessor:

class Person
  attr_accessor :name
end
Enter fullscreen mode Exit fullscreen mode

Putting it all together. Let's make a class, lets call it Person, with a variable (name). With attr_accessor, you can gain the ability to read and write to the name variable outside the class scope.

class Person
  attr_accessor :name
end

person = Person.new

person.name = "Educative" # you can both modify ...
puts person.name          # ... and read variable
Enter fullscreen mode Exit fullscreen mode

Top comments (0)