class Song
def initialize(name,artist,duration)
@name = name
@artist = artist
@duration = duration
end
def to_s
"Song : #{@name}--#{@artist} (#{@duration})"
end
end
class SongList
def initialize
@songs = Array.new
end
def append(aSong)
@songs.push(aSong)
self
end
def show=(index)
#puts "show #{index}"
#puts "@songs.length : #{@songs.length}"
#puts "@songs[#{index}] : #{@songs[index]}"
@songs[index]
end
def show(index)
@songs[index]
end
def [](key)
if key.kind_of?(Integer)
@songs[key]
else
end
end
def size
@songs.length
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))
#puts(list.show = 1)
p list.show = 2 >> 2
p list.show(2) >>#<Song:0x2b36d28 @duration=3, @artist="artist3", @name="title3">
p list[2] >>#<Song:0x2b36d28 @duration=3, @artist="artist3", @name="title3">
疑问:
为什么调用 list.show = 2 返回的是2 ?
不是应该和list.show(2)一样 返回的是@Songs[2]的 Song实例 吗?