Why does this error happen?


#1

Hello,

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'"
else
    print "Does not contain an 's'"
end

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!

to:

user_input = gets.chomp
user_input.downcase!

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

Thanks,


#2

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

gets.chomp.downcase!.include?

But even so, why doesn't it work?


#3

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.


#4

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