What is attr_reader in Ruby?

In Ruby, object methods are public by default, while data is private. To access datainstance variables, we use the accessor method, attr_reader.

Usage

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.

Code

Let’s make a class (Person) with a variable (name). Using attr_reader, you can read the variable name outside the class scope.

class Person
attr_reader :name
def initialize(name)
@name = name
end
end
person = Person.new("Educative")
puts person.name # Read variable

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved