Ruby 打印出数组会产生奇怪的输出
我有一个曲目数组,它位于另一个称为albums的数组中。我有以下代码,允许用户输入Ruby 打印出数组会产生奇怪的输出,ruby,Ruby,我有一个曲目数组,它位于另一个称为albums的数组中。我有以下代码,允许用户输入相册[索引],如果存在,允许用户输入曲目[索引]。如果这也存在,那么这些索引中的唱片集和曲目将被打印出来 但是,当我运行代码时,我得到的不是唱片集名称和曲目名称,而是以下输出: The selected track is The selected track is #<Track:0x2fca360> #<Album:0x2fca960> 默认情况下,#to_s返回对象类的名称和对象id
相册[索引]
,如果存在,允许用户输入曲目[索引]
。如果这也存在,那么这些索引中的唱片集和曲目将被打印出来
但是,当我运行代码时,我得到的不是唱片集名称和曲目名称,而是以下输出:
The selected track is The selected track is #<Track:0x2fca360> #<Album:0x2fca960>
默认情况下,#to_s
返回对象类的名称和对象id
如果您为Tack
和Album
实现自己的#to#s
方法,那么您会得到正确的结果
class Track
def to_s
name
end
end
class Album
def to_s
name
end
end
最好是显式地调用#name
。
将“所选曲目为”+tracks[j]。name+“”+albums[index]。name
您为什么认为track#to#s
或Album#to#s
会输出其名称?您可能应该使用tracks[j].name”和
albums[index].name`来代替。put“所选曲目是”+tracks[j].name+“”+albums[index].name
通常会写为put“所选曲目是#{tracks[j].name}{albums[index].name}”
。Ruby当然更喜欢插值而不是串联。整个脚本可以用Ruby的方式重写。
def main
# fix the following two lines
music_file = File.new("albums.txt", "r")
albums = read_albums_file(music_file)
tracks = read_tracks(music_file)
print_albums(albums)
music_file.close()
play_selected_track(albums,tracks)
end
class Track
def to_s
name
end
end
class Album
def to_s
name
end
end