In Ruby, object methods are public by default, while data is private. To access attr_reader
.
Suppose you want to read the instance variables of an object. Normally, you would define getter
methods to access the variables:
class Person
def name
@name
end
end
This is a very common pattern, so Ruby has the accessor method attr_reader
. The above code can be condensed to:
class Person
attr_reader :name
end
Writing it this way is not only idiomatic; it’s also has a slight performance advantage.
Let’s make a class (Person
) with a variable (name
). Using attr_reader
, you can read the variable name outside the class scope.
class Personattr_reader :namedef initialize(name)@name = nameendendperson = Person.new("Educative")puts person.name # Read variable
Free Resources