From: Paul Mckibbin Date: 2011-02-11T01:02:22+09:00 Subject: Re: attr_reader vs Objects and Attributes Mike Onofrietto wrote in post #980715: > Hello World. > This is my first forum membership, and first post. > I am learning Ruby. > It seems to be a very elegant an encompassing OO language. > I'm reading Thomas & Hunt: Classes, Objects, and Variables on-line. > > See attached. > > Regarding the following by the authors, and attached I see no > correlation. > However I've had very good results with attr_accessor. > Please help. > In your test code, and the attachment, you don't have an initialize function, which is defined in the first page of the book: i.e. class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end end The way Ruby works is that if this is defined, even if you have a new class block i.e. class Song def name; @name; end def artist; @artist; end def song; @song; end end that doesn't overwrite the previous definition. It EXTENDS it. So now your class should be (in memory anyway) equivalent to: class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end def name; @name; end def artist; @artist; end def song; @song; end end Without the initialization, you are called the base class Object.new(*arr) method, which will not assigned any class variables for you, regardless of whether you use attr_x methods or not. Mac. -- Posted via http://www.ruby-forum.com/.