Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby

What is attr_accessor in Ruby?

Nouman Abbasi

In Ruby, object methods are public by default, while data is private. To access and modify data, we use the attr_reader and attr_writer.

attr_accessor is a shortcut method when you need both attr_reader and attr_writer. Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.

Usage

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

class Person
  def name
    @name
  end

  def name=(str)
    @name = str
  end
end

However, all of the above could be written in a more idiomatic way using attr_accessor:

class Person
  attr_accessor :name
end

Code

Let’s make a class (Person) with a variable (name). Using attr_accessor, you can 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

RELATED TAGS

ruby

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring