[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Listing an Array created within a Class

Adrian Arlechin

5/30/2009 5:48:00 PM

I am learning from Programming Ruby wich comes with Ruby instalation.
In the chapter about containers - Implementing a SongList Container
I took the code in NetBeans like follows:

require 'Baza.rb' #here is my Song class
class SongList < Song
def initialize
@songs = Array.new
end
end

class SongList
def append(aSong)
@songs.push(aSong)
self
end
end

list = SongList.new
list.
append(Song.new('title1', 'artist1', 1)).
append(Song.new('title2', 'artist2', 2)).
append(Song.new('title3', 'artist3', 3)).
append(Song.new('title4', 'artist4', 4))

############# Here is my problem
puts list.to_a ?????????
What line must I have here to have at terminal the array that is created
in the SongList like this:
Song: title1--artist1 (1)
Song: title2--artist2 (2).... etc , so that I can work with it?
and/or to see the list elements with list[0, 2]
Thanks
--
Posted via http://www.ruby-....

3 Answers

MK

5/30/2009 6:41:00 PM

0

list.each
--
Posted via http://www.ruby-....

Brian Candler

5/30/2009 6:48:00 PM

0

Adrian Arlechin wrote:
> I am learning from Programming Ruby wich comes with Ruby instalation.
> In the chapter about containers - Implementing a SongList Container
> I took the code in NetBeans like follows:
>
> require 'Baza.rb' #here is my Song class
> class SongList < Song
> def initialize
> @songs = Array.new
> end
> end
>
> class SongList
> def append(aSong)
> @songs.push(aSong)
> self
> end
> end
>
> list = SongList.new
> list.
> append(Song.new('title1', 'artist1', 1)).
> append(Song.new('title2', 'artist2', 2)).
> append(Song.new('title3', 'artist3', 3)).
> append(Song.new('title4', 'artist4', 4))
>
> ############# Here is my problem
> puts list.to_a ?????????

class SongList
def to_a
@songs
end
end

puts list.to_a

OR:

class SongList
attr_accessor :songs
end

puts list.songs

OR: another way is to make your SongList class duck-type like an Array

class SongList
def [](elem)
@songs[elem]
end
def []=(elem,obj)
@songs[elem] = obj
end
# ... etc
end
--
Posted via http://www.ruby-....

Adrian Arlechin

5/31/2009 5:09:00 AM

0


Thank you Brian very much, it works!
Hmmm, how stupid I am. I have learned about this in the previous lesson.
That's the begining, but it's very well that is this forum.

Adrian
--
Posted via http://www.ruby-....