Ruby如何循环执行专辑读取代码并按规则控制music_file.gets执行次数
方案1:按指定次数控制gets执行次数
你可以给read_album方法新增一个控制跳过行数的入参,循环时把对应次数传入即可,实现代码如下:
# 新增skip_lines参数控制开头gets的执行次数 def read_album(music_file, skip_lines) skip_lines.times { 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 # 按需求定义每次循环要执行的gets次数,顺序对应循环顺序 skip_counts = [1, 5, 8] 3.times do |index| read_album(music_file, skip_counts[index]) end
方案2:适配文件格式的更优实现
结合你给出的Albums.txt结构,其实不需要硬编码跳过行数,直接按文件规则读取即可,可维护性更高,也不会因为后续曲目数量变化而出错:
File.open("Albums.txt", "r") do |music_file| # 读取第一行总专辑数 album_total = music_file.gets.to_i # 循环读取所有专辑,不需要硬编码次数 album_total.times do artist = music_file.gets.chomp # chomp用于去掉行尾换行符 title = music_file.gets.chomp track_count = music_file.gets.to_i # 按读取到的曲目数读对应行数的曲目 tracks = [] track_count.times do tracks << music_file.gets.chomp end album = Album.new(artist, title, track_count, tracks) print_album(album) end end
注意事项
- 调用
gets会自动将文件指针移动到下一行,不需要手动控制文件偏移,按文件顺序读取即可 - 如果你原代码里的
album_genre就是文件里的曲目数字段,建议修改变量名避免歧义
内容的提问来源于stack exchange,提问作者Theo1290
相关产品推荐
相关产品推荐

