【问题标题】:Is there a way to loop something multiple times specifically有没有办法专门循环多次
【发布时间】:2021-12-08 05:18:55
【问题描述】:

我有

def read_album(music_file)
  music_file.gets
  album_artist = music_file.gets
  album_title = music_file.gets
  album_genre = music_file.gets.to_i
  tracks = read_tracks(music_file)
  album = Album.new(album_artist, album_title, album_genre, tracks)
  print_album(album)
end

我想循环整个块 3 次(可能使用类似 3.times 的东西),但是让 music_file.gets(过程中的第一行)在每个循环中运行不同的次数。 (说在第一个循环中只有一次,在第二个循环中为 5 次,在第三个循环中为 8 次。)我不确定是否有办法添加索引并以某种方式使索引从每个循环的特定值发生变化并且有music_file.gets 根据那个或其他方式重复。

编辑:文本文件有一组专辑,格式类似于:我想使用曲目数量作为循环读取专辑信息的控制变量,music_file.gets 是获取该信息.

Albums.txt (the file name, everything below is a separate line of text in the file)
*Number of albums (integer)
*Artist name
*Album name
*Number of Tracks (integer)
*Track 1
*Track 2
*Artist Name
*Album name
*Number of Tracks (integer)
*Track 1
*Track 2
*Track 3
etc. (number of tracks per album are random)

【问题讨论】:

  • 你也可以在 n.times do 中设置 n 为任何你喜欢的。
  • “让 music_file.gets 在每个循环中运行不同的次数” – 你为什么要这样做?数字(3 / 5 / 8)从何而来?你能解释一下你正在读取的文件的结构吗?可以举个例子吗?
  • music_file.gets 去掉换行符吗?
  • 请显示您的数据,而不仅仅是您的代码。否则,无法验证预期的输入和输出。
  • 您似乎正在尝试从文本文件中扫描数据。我建议查看StringScanner class

标签: ruby loops procedure


【解决方案1】:

给定一对通过读取获得的计数,您可以使用嵌套循环结构。计数的两种基本机制是count.timesRange.each,如下所示:

number_of_albums.times do |i|    # i goes from 0 to m-1
  # do album stuff, including picking up the value of number_of_tracks
  (1..number_of_tracks).each do |j|    # j goes from 1 to number_of_tracks
    # do track stuff
  end
  # do additional stuff if needed
end

如果要完成的“东西”是单行的,您可以用花括号替换 do/end。

有关各种循环选项的更多信息,请参阅此tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多