Trusted answers to developer questions

What is attr_reader in Ruby?

Nouman Abbasi

Free System Design Interview Course

Get Educative's definitive System Design Interview Handbook for free.

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 ©2023 Educative, Inc. All rights reserved
Trusted Answers to Developer Questions

Related Tags

ruby
Keep Exploring
Related Courses