我不明白为什么以下不起作用:
#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
: : : :
这是编程Ruby书中的一个例子。我不知道为什么scan方法和squeeze方法在它们是字符串对象而不是nilClass对象时抛出错误。没有这些,输出歌曲[1]的输出看起来是正确的。
答案 0 :(得分:3)
最后一行
::::
与拆分不匹配,因此name,length和title为nil
文件最终为
::::
一个平行的例子:
a,b,c = [1,2]
#a=1
#b=2
#c = nil