What is attr_reader in Ruby: Simple Explanation and Example
attr_reader in Ruby is a shortcut to create a method that lets you read (access) an instance variable from outside the class. It automatically defines a getter method, so you don't have to write it yourself.How It Works
Imagine you have a box (an object) with a label (an instance variable) inside. Normally, to see what's inside the box, you need a way to open it safely. In Ruby, attr_reader creates a small door (a method) that lets you peek inside without changing anything.
When you write attr_reader :name, Ruby automatically makes a method called name that returns the value of the @name variable. This saves you from writing the same simple method over and over.
Example
This example shows how attr_reader creates a getter method for an instance variable.
class Person attr_reader :name def initialize(name) @name = name end end person = Person.new("Alice") puts person.name
When to Use
Use attr_reader when you want to allow other parts of your program to read an object's data but not change it directly. For example, if you have a Person class and want to let others see the person's name but not modify it, attr_reader is perfect.
This helps keep your data safe and your code clean by avoiding extra methods.
Key Points
- attr_reader creates getter methods automatically.
- It allows read-only access to instance variables.
- Saves time by reducing boilerplate code.
- Helps keep data safe by preventing direct modification.
Key Takeaways
attr_reader creates a simple way to read instance variables from outside a class.