2016-07-08 36 views
-1

我有以下代碼,它在單詞中查找字母「u」和「e」,並向索引添加1以顯示在單詞中從1開始而不是0,然後將它組合成一個數組。Ruby「#<NoMethodError:undefined method`+'for nil:NilClass>」

def vowel_indices(word) 
    x = (word.index("u") + 1) 
    y = (word.index("e") + 1) 
    print = [x,y] 
end 

我正在運行時,出現以下錯誤信息:

#<NoMethodError: undefined method `+' for nil:NilClass> 

什麼是零在這?從我可以看到我的變量分配正確。

+0

什麼是'word'的價值? –

+0

我正在測試的這個詞是「超級」。但是,可變字中沒有存儲值。 – John

+0

當我用'vowel_indices(「super」)運行你的代碼時,它工作正常。錯誤在別處。你打算怎麼調用這個方法? –

回答

0

這是因爲對於word指定的某些值可能不包含ue

如果您使用Rails,那麼你可以通過修改你這樣的代碼解決這個問題:

def vowel_indices(word) 
    x = (word.try(:index, "u").try(:+, 1) 
    y = (word.try(:index, "e").try(:+, 1) 
    print = [x,y] 
end 

通過這種方式,可以防止試圖調用:+方法如果類是Nil的方法。

在我們不確定輸入信息的情況下,最好使用try

+0

@CarySwoveland,謝謝你指出。我的錯誤,我認爲他使用Rails。我相應地修改了我的答案:) – Lahiru

1

「這是什麼零?」

正如@卡里Swoveland和@Lahiru已經說過,如果一個詞是在通過不具有「U」或「e」這將引發異常:

001 > def vowel_indices(word) 
002?>  x = (word.index("u") + 1) #word.index("u") returns nil if the word arg passed in doesn't have a 'u' 
003?>  y = (word.index("e") + 1) 
004?>  print = [x,y]  #I've never seen the 'print =' syntax...any reason you're not just returning [x,y] here? 
005?> end 
=> :vowel_indices 
006 > vowel_indices("cruel") 
=> [3, 4] 
007 > vowel_indices("cat") 
NoMethodError: undefined method `+' for nil:NilClass 
    from (irb):2:in `vowel_indices' # This tells you exactly where the exception is coming from 
    from (irb):7 
    from /Users/kenenitz/.rvm/rubies/ruby-2.2.0/bin/irb:11:in `<main>' 

兩個快速&髒的方式來處理,這將是要麼添加一個條件來檢查每個字母的存在,或者你可以拯救NoMethodError

#conditional check (preferred as it is more precise) 
def vowel_indices(word) 
    u_index = word.index("u") 
    e_index = word.index("e") 
    x = u_index ? u_index + 1 : nil #verify that u_index is not nil before calling :+ method 
    y = e_index ? e_index + 1 : nil # same for e_index 

    [x,y] 
end 

#rescuing NoMethodError, not preferred in this case but including as a possible solution just so that you're familiar w/ this approach 

def vowel_indices(word) 
    begin 
    x = word.index("u") + 1 
    y = word.index("e") + 1 
    rescue NoMethodError 
    x = nil 
    y = nil 
    end 
    [x,y] 
end 

無論使用哪種解決方案,我提供,如果某個單詞缺少一個「U」或' e',返回值將包含nil,最有可能需要在其他地方你的程序某種特殊處理:

vowel_indices("cat") 
=> [nil, nil] 

vowel_indices("cut") 
=> [2, nil] 
0
word = "Hello" # example 

def vowel_indices(word) 
    x = (word.index("u") + 1) # x = (nil + 1) *There is no "u" in "Hello" 
    y = (word.index("e") + 1) # y = (1 + 1) *Output as expected based on index 
    print = [x,y] 
end 

p word.index("u") # will return nil if you need to check the return value 
相關問題