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

时间:2020-05-18 14:13:45

标签: ruby

我有一个阵列音轨,位于另一个称为专辑的阵列中。我有以下代码,该代码允许用户输入albums[index],如果存在,则允许用户输入tracks[index]。如果还存在,则会打印出出现在这些索引处的专辑和曲目。

但是,当我运行代码时,没有得到专辑名称和曲目名称,而是得到以下输出:

The selected track is The selected track is #<Track:0x2fca360> #<Album:0x2fca960>

以下是相关的代码段:

def play_selected_track(albums,tracks)
  # ask user to enter ID number of an album in the albums-list

  puts "Enter album id:"
  album_id = gets.chomp
  index = 0

  while (index<albums.length)
    if (album_id=="#{index}")
      puts "Please enter track id:"
      track_id = gets.chomp
      j = 0
      while (j<tracks.length)

        if (track_id == "#{j}")
          puts "The selected track is " + tracks[j].to_s + " " + albums[index].to_s
        end
        j += 1
      end 
    end 
    index += 1
  end 
end 
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

1 个答案:

答案 0 :(得分:1)

默认情况下,#to_s返回对象的类名和对象ID https://apidock.com/ruby/Object/to_s

如果为#to_sTack实现自己的Album方法,那么您将获得正确的结果。

class Track
  def to_s
    name
  end
end

class Album
  def to_s
    name
  end
end

最好是显式调用#nameputs "The selected track is " + tracks[j].name + " " + albums[index].name