In Ruby, object methods are public by default, while data is private. To access and modify data, we use the
attr_accessor is a shortcut method when you need both
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
class Person attr_accessor :name end
Let’s make a class (
Person) with a variable (
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
View all Courses