Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 打印出数组会产生奇怪的输出_Ruby - Fatal编程技术网

Ruby 打印出数组会产生奇怪的输出

Ruby 打印出数组会产生奇怪的输出,ruby,Ruby,我有一个曲目数组,它位于另一个称为albums的数组中。我有以下代码,允许用户输入相册[索引],如果存在,允许用户输入曲目[索引]。如果这也存在,那么这些索引中的唱片集和曲目将被打印出来 但是,当我运行代码时,我得到的不是唱片集名称和曲目名称,而是以下输出: The selected track is The selected track is #<Track:0x2fca360> #<Album:0x2fca960> 默认情况下,#to_s返回对象类的名称和对象id

我有一个曲目数组,它位于另一个称为albums的数组中。我有以下代码,允许用户输入
相册[索引]
,如果存在,允许用户输入
曲目[索引]
。如果这也存在,那么这些索引中的唱片集和曲目将被打印出来

但是,当我运行代码时,我得到的不是唱片集名称和曲目名称,而是以下输出:

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