Trusted answers to developer questions

What is attr_reader in Ruby?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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

RELATED TAGS

ruby

CONTRIBUTOR

Nouman Abbasi
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?