我目前正在自學 Ruby 并正在練習方法。所以,我似乎不明白為什么我的控制臺在列印正確的條件后不斷列印出錯誤訊息。任何解釋將不勝感激!
def test(tester)
if tester
puts "yes";
else
puts "error";
end
end
#call function
test(:tester).("hello world");
輸出:
yes
main.rb:10:in `<main>': undefined method `call' for nil:NilClass (NoMethodError)
為什么我會收到此錯誤?
uj5u.com熱心網友回復:
foo.(bar)是 . 的語法糖foo.call(bar)。所以,test(:tester).("hello world")是test(:tester).call("hello world").
但是,testreturns nil,所以您呼叫nil.("hello world")的方法與 相同nil.call("hello world"),如果您查看的檔案NilClass,您可以很容易地看到它沒有名為 的方法call。(NilClass繼承自Objectwhich 又繼承自Kerneland BasicObject,因此理論上,可以在此處定義該方法,但是您可以輕松地檢查自己,但事實并非如此。)
由于您正在呼叫一個不存在的方法,因此您會得到一個NoMethodError.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486273.html
標籤:红宝石
