ruby - 有没有办法专门循环多次
问题描述
我有
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。
有关各种循环选项的更多信息,请参阅本教程。
推荐阅读
- flutter - 是否可以在飞镖中动态设置方法的返回类型
- python - 在 Android Studio 中使用 Chaquopy 将值插入到 python 文件中
- vba - 从抓取的表格中提取单元格值的最有效方法
- c# - 是否可以在 HwndHost 中托管 WPF 页面?
- chart.js - 如何在工具提示回调afterBody中将逗号分隔的字符串分成新行?
- stata - 在stata矩阵中生成新列
- python - I am trying to call information on venues in a 500 m radius of a location via the foursquare API. I keep getting getting the error: [WinError 10061]
- javascript - How to use chartkick and vue in html?
- flutter - how to config ignore null check in release mode with flutter build
- reactjs - Cannot import image in NextJs project