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实例 吗?
Ruby类定义与实例化
本文介绍了一段使用Ruby语言定义歌曲类及歌曲列表类的代码实现,详细展示了类的初始化、实例化以及如何通过索引访问特定元素的过程。文章中提出的问题在于对列表类中元素访问方法的理解差异。
146

被折叠的 条评论
为什么被折叠?



