Forum: Ruby A question about attr_reader

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Akbar P. (Guest)
on 2006-05-04 17:52
(Received via mailing list)
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
Patrick H. (Guest)
on 2006-05-04 18:07
(Received via mailing list)
On 5/4/06, Akbar P. <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
Akbar P. (Guest)
on 2006-05-04 21:18
(Received via mailing list)
Thanks Patrick. You were right about the constructor call. It was my
mistake. Now without it, it returns nil as you indicated.

::akbar
This topic is locked and can not be replied to.