2013-09-22 47 views
-1

下面是一些代碼:未定義的方法`include?'對於零:NilClass紅寶石初學者

print "What is your name?" 
userinput = gets.chomp.downcase! 
if userinput.include? "s" 
    print "I found it" 
else 
    print "found nothing" 
end 

它給人的錯誤:未定義的方法`包括」對於零:NilClass

但是當我將其更改爲:

print "What is your name?" 
userinput = gets.chomp 
userinput.downcase! 
if userinput.include? "s" 
    print "I found it" 
else 
    print "found nothing" 
end 

它工作得很好。任何想法爲什麼這是?

回答

0

downcase!返回nil什麼時候什麼都不是。如果您將其重新分配到userinput,那麼userinput可以變成nil,如第一個示例中所示。如果您使用downcase,那麼錯誤將消失。在第二個示例中,您不重新指定downcase!userinput的結果,因此userinput不會被覆蓋爲nil

+0

感謝您的澄清。 –

相關問題