我不明白为什么以下不起作用:
#TODO:
#Open file-io-samples/MultipleLinesCustomDelimiter.txt
#Break each line into fields
#Convert Times from mm:ss to seconds
#Remove any redundant spaces.
#######################################################
Song = Struct.new(:title, :name, :length)
File.open("file-io-samples/MultipleLinesCustomDelimiter.txt") do |file_data|
songs = []
file_data.each do |line|
file, length, name, title = line.chomp.split(/\s*\|\s*/)
name.squeeze!(" ") #Error: undefined method for nilClass
mins, secs = length.scan(/\d+/) #Error: undefined method for nilClass
secs += mins*60
songs << Song.new(title, name, secs)
end
puts songs[1] #make sure output is consistent.
end
正在读取的文件内容:
/jazz/j00132.mp3 | 3:45 | Fats Waller | Ain't Misbehavin'
/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World
/bgrass/bg0732.mp3| 4:09 | Strength in Numbers | Texas Red
: : : :
这是 Programming Ruby 书中的一个示例。我不知道为什么扫描方法和挤压方法在它们是字符串对象而不是 nilClass 对象时会抛出错误。没有这些, puts song[1] 的输出看起来是正确的。