2013-05-14 42 views
0

我不明白爲什麼下面不工作:文件的紅寶石方法未定義nilClass錯誤的字符串方法

#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書籍的例子。我不知道爲什麼scan方法和squeeze方法在字符串對象不是nilClass對象時拋出錯誤。如果沒有這些,put songs [1]的輸出看起來是正確的。

+0

他們說他們是'nilClass',不'String'。 – sawa

+0

我知道,但我不明白他們如何不能串。 – Senjai

回答

3

最後一行

::

不匹配的分裂,所以名稱,長度和標題爲

文件結束

::::

並行例如:

a,b,c = [1,2] 
#a=1 
#b=2 
#c = nil 
+0

啊,我的意思是用它來檢測文件的結尾。對我而言,這是多麼的疏忽。謝謝您的幫助。冷卻後我會標記答案。 – Senjai

+0

不客氣,不幸的是,這些例外情況並不多,所以這是使用戰略性投入語句或調試器的問題。 –

+0

是的,這是我的一個非常簡單的錯誤。 – Senjai

相關問題