Forum: Ruby Listing an Array created within a Class

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.
781a4b62ad407738d5c547b7cedce2d3?d=identicon&s=25 Adrian Cinta (adrian-cinta)
on 2009-05-30 19:47
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
68814ed988eee4f21b2cd07353e5e445?d=identicon&s=25 Mk 27 (mk27)
on 2009-05-30 20:40
list.each
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2009-05-30 20:48
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
781a4b62ad407738d5c547b7cedce2d3?d=identicon&s=25 Adrian Cinta (adrian-cinta)
on 2009-05-31 07:09
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
This topic is locked and can not be replied to.