From: Robert Dober Date: 2006-06-07T05:46:23+09:00 Subject: Re: Attributes not populated until called? ------=_Part_52663_2530080.1149626778685 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 6/6/06, darren kirby wrote: > > Hello all, > > Pretty much new to Ruby, and I think I am not grasping something > fundamental > here. I've written some classes that grab meta tags from various audio > file > formats, and overrode 'to_s" to dump the tags to the console, and "to_a" > to > dump the tags to an array for use elsewhere in my program. > > I am not sure how to explain my problem, so I will just paste in a sessio= n > from irb that shows it: > > irb> require 'sneetchalizer' # my class definitions... > irb> x =3DOggMetaTags.new('/home/music/e/elliottSmith-shootingStar.ogg') All instance variables are defaulting to nil, none of the instance variable= s set in the initializer, are used in to_a, so to_a converts nil to a string which happens to be an empty string. =3D> # irb> x.to_a > =3D> ["", "", "", "", "", "", ""] > irb> x.title =3D> "Shooting Star" The title method sets the instance variable @title, therefore to_a yields ... irb> x.to_a > =3D> ["Shooting Star", "", "", "", "", "", ""] idem irb> x.artist > =3D> "Elliott Smith" > irb> x.to_a > =3D> ["Shooting Star", "Elliott Smith", "", "", "", "", ""] > > So you can see I need to explicitly call each attribute before my array > gets > the value. How can I change this so the array is populated automatically > when > called? Here is the class: > > class OggMetaTags < MetaTags > def initialize(filename) > @filename =3D filename > require 'ogginfo' > @tags =3D OggInfo.new(@filename) > end > def title > @title =3D @tags.tag['title'] > end > def artist > @artist =3D @tags.tag['artist'] > end > def album > @album =3D @tags.tag['album'] > end > def genre > @genre =3D @tags.tag['genre'] > end > def year > @year =3D @tags.tag['date'] > end > def comment > @comment =3D super > end > def tracknum > @tracknum =3D @tags.tag['tracknumber'] > end > > def to_a > ["#@title", "#@artist", "#@album", "#@genre", "#@year", "#@comment", > "#@tracknum"] > end > end > > If you need more info or want to see all the code please just ask. Thanks > for > consideration, No the programmatic behavior is clear, I fail to see the reason though, but there might be one. As a matter of fact there is a good reason to cache the value of the attribute in the reader but that would be done like this @year =3D @tags.tag['date'] -d > -- > darren kirby :: Part of the problem since 1976 :: http://badcomputer.org > "...the number of UNIX installations has grown to 10, with more > expected..." > - Dennis Ritchie and Ken Thompson, June 1972 > > > --=20 Deux choses sont infinies : l'univers et la b=EAtise humaine ; en ce qui concerne l'univers, je n'en ai pas acquis la certitude absolue. - Albert Einstein ------=_Part_52663_2530080.1149626778685--