Why does this error happen?



I'm just curious as to why the following occurs:

If my code is like the following:

print "Type in a string pleaaassee:"

user_input = gets.chomp.downcase!

if user_input.include? "s"
    print "It contains an 's'"
    print "Does not contain an 's'"

Then I get the following error:

Type in a string pleaaassee: s
undefined method `include?' for nil:NilClass

But if I change the following line:

user_input = gets.chomp.downcase!


user_input = gets.chomp

Then it works just fine.. Can someone explain why?



Is it because the code that gets executed ends up looking like this?


But even so, why doesn't it work?


Calling methods on nil doesn't make much sense. You got that nil value from a function, perhaps the way you use that function doesn't very well match the behaviour that this function exhibits. You can find out if that's the case by looking up the documentation for how that function behaves.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.