有没有办法专门循环多次
Is there a way to loop something multiple times specifically
我有
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)
给定一对通过阅读获得的计数,您可以使用嵌套循环结构。计数的两种基本机制是 count.times
或 Range.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。
我有
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)
给定一对通过阅读获得的计数,您可以使用嵌套循环结构。计数的两种基本机制是 count.times
或 Range.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。