0

What is the difference between using @name and name (with an attr_reader)? They use different path ways: @name is direct while name uses a method to reach @name. But besides that, is there any difference? The outcome is the same.

sawa
  • 160,959
  • 41
  • 265
  • 366
Bri Expost
  • 67
  • 7

1 Answers1

2

But besides that is there any difference because the outcome is the same.

Besides that? Not much. It's just that attr_reader gives you a method (as you already know), so you can do all the things you do to methods: make public/private, decorate, override in a child class, include from a module, etc.

Oh, and also instance variables are harder to access from outside the class. Which is why attr_reader and related helpers exist in the first place (to easily wrap ivars in public methods).

Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354