How to Use the Ruby attr_reader Method
In this article, you will learn how to use the Ruby attr_reader method.
Using the attr_reader method
In Ruby, the attr_reader method is a built-in method that helps to create getter methods for class attributes. This method generates a simple method that returns the value of an instance variable with the same name as the method. Here’s how you can use the attr_reader method in your Ruby class:
Define your class and instance variables:
class Person def initialize(name, age) @name = name @age = age end end
Use the attr_reader method to generate getter methods for the instance variables:
class Person attr_reader :name, :age def initialize(name, age) @name = name @age = age end end
Access the instance variables using the generated getter methods:
person = Person.new("John", 30) puts person.name #=> "John" puts person.age #=> 30
In the above example, the attr_reader method has generated two methods: name and age. These methods can be called on an instance of the Person class to access the @name and @age instance variables respectively.
You can also use the attr_reader method to generate getter methods for multiple instance variables at once:
class Person attr_reader :name, :age, :gender def initialize(name, age, gender) @name = name @age = age @gender = gender end end
In this example, the attr_reader method has generated three methods: name, age, and gender. These methods can be used to access the @name, @age, and @gender instance variables respectively.