# A question about attr\_reader

**URL:** <https://www.ruby-forum.com/t/a-question-about-attr-reader/59603>\
**Category:** Ruby\
**Created:** [May 4, 2006, 3:52pm UTC](https://www.ruby-forum.com/t/a-question-about-attr-reader/59603 "2006-05-04T15:52:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Akbar\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecccb3/32.png) [@Akbar\_P](https://www.ruby-forum.com/u/Akbar_P)\
**Post date:** [May 4, 2006, 3:52pm UTC](https://www.ruby-forum.com/t/a-question-about-attr-reader/59603/1 "2006-05-04T15:52:05Z")

</div>

Hi All,

I am just going through the pickacxe book and have a question about  
attr\_reader. Here is the sample class.

class Song  
def initialize(name, artist, duration)  
@name = name  
@artist = artist  
@duration = duration  
end  
end

It says I can do the following-

class Song  
def name  
@name  
end  
def artist  
@artist  
end  
def duration  
@duration  
end  
end

OR

I can do the following-

class Song  
attr\_reader :name, :artist, :duration  
end

This is fine, but it says “The corresponding instance variables, @name,  
@artist, and @duration, will be created automatically” (on Page 31)  
about  
attr\_reader. I kinda thought that those variables are already created  
when  
“initialize” function is called. If I comment the initialize function  
and  
run it - I get an error.

So what does the author mean by that?

Thanks in advance,

::akbar

---

<div class="post-metadata">

**Author:** ![Akbar\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecccb3/32.png) [@Akbar\_P](https://www.ruby-forum.com/u/Akbar_P)\
**Post date:** [May 4, 2006, 7:18pm UTC](https://www.ruby-forum.com/t/a-question-about-attr-reader/59603/2 "2006-05-04T19:18:22Z")

</div>

Thanks Patrick. You were right about the constructor call. It was my  
mistake. Now without it, it returns nil as you indicated.

::akbar

---

<div class="post-metadata">

**Author:** ![Akbar\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecccb3/32.png) [@Akbar\_P](https://www.ruby-forum.com/u/Akbar_P)\
**Post date:** [May 4, 2006, 4:07pm UTC](https://www.ruby-forum.com/t/a-question-about-attr-reader/59603/3 "2006-05-04T16:07:20Z")

</div>

On 5/4/06, Akbar P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> end
> 
> ```
> 
> end  
> attr\_reader :name, :artist, :duration  
> Thanks in advance,
> 
> ::akbar

Maybe this will help clarify:

class Foo  
attr\_reader :bar

def go\_to\_the\_bar  
@bar = ‘anytime’  
end  
end

foo = Foo.new  
p foo.bar  
foo.go\_to\_the\_bar  
p foo.bar

There is no error, accessing the instance variable @bar, from the  
reader (it has a value of nil) – it is created on the fly. I am  
guessing you commented out your initialize, but were still calling the  
constructor with parameters?

pth
