「這是什麼零?」
正如@卡里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]
什麼是'word'的價值? –
我正在測試的這個詞是「超級」。但是,可變字中沒有存儲值。 – John
當我用'vowel_indices(「super」)運行你的代碼時,它工作正常。錯誤在別處。你打算怎麼調用這個方法? –