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.
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
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 Personattr_accessor :nameendperson = Person.newperson.name = "Educative" # you can both modify ...puts person.name # ... and read variable
Free Resources