【发布时间】: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去掉换行符吗? -
请显示您的数据,而不仅仅是您的代码。否则,无法验证预期的输入和输出。
-
您似乎正在尝试从文本文件中扫描数据。我建议查看
StringScannerclass。