【问题标题】:Printing out array gives strange output打印出数组会产生奇怪的输出
【发布时间】:2020-05-18 14:13:45
【问题描述】:

我有一个数组曲目,它位于另一个称为专辑的数组中。我有以下代码允许用户输入albums[index],如果存在,则允许用户输入tracks[index]。如果这也存在,则打印出这些索引中存在的专辑和曲目。

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

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

这里是相关代码sn-ps:

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

【问题讨论】:

  • 为什么你认为Track#to_sAlbum#to_s 会输出它的名字?你应该改用tracks[j].name' and albums[index].name`。

标签: ruby


【解决方案1】:

默认#to_s返回对象的类名和对象idhttps://apidock.com/ruby/Object/to_s

如果您为TackAlbum 实现自己的#to_s 方法,那么您会得到正确的结果。

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

【讨论】:

  • puts "The selected track is " + tracks[j].name + " " + albums[index].name 通常写作puts "The selected track is #{tracks[j].name} #{albums[index].name}"。 Ruby 更喜欢插值而不是串联
  • 当然。整个脚本可以用 Ruby 的方式重写。
猜你喜欢
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 2021-07-26
  • 1970-01-01
相关资源
最近更新 更多