是否有一种方法可以循环多次



我有

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。),但有music_file。获取(过程中的第一行)每个循环运行不同的次数。(比如第一次循环一次,第二次循环5次,第三次循环8次。)我不确定是否有一种方法可以添加索引,并以某种方式从每个循环的特定值更改索引,并拥有music_file。按此或其他方式得到重复。

编辑:文本文件有一组专辑,有一个类似于这样的格式:我想使用轨道的数量作为一个控制变量的循环读取专辑信息,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)

给定一对通过读取获得的计数,可以使用嵌套循环结构。计数的两个基本机制是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。

有关循环选项的更多信息,请参阅本教程。

最新更新