reFORtEM
reFORtEM

Reputation: 941

Error when chaining with chomp

I wrote a small program as the following

print "Your string = "
input = gets.chomp.downcase!

if input.include? "s"
   puts "Go yourself!"
end

But I got the error

undefined method `include?' for nil:NilClass (NoMethodError)

if I delete the exclamation mark (!) after downcase, the program runs properly.

I don't understand the reason.

Upvotes: 2

Views: 617

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

String#downcase! will give you nil, if the string is already in down-cased. So use String#downcase, it is safe. I am sure, you passed from the command line to the method gets, a string which is already down-cased. Replace the line input = gets.chomp.downcase! with input = gets.chomp.downcase. Now you are safe.

String#downcase

Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. If the receiver string object is already, downcased, then the receiver will be returned.

String#downcase!

Downcases the contents of str, returning nil if no changes were made.

One example to demonstrate this -

>> s = "abc"
>> p s.downcase
"abc"
>> p s.downcase!
nil

Now nil is an instance of the class NilClass, which has no instance method called #include?. So you got no method error. This is obvious.

>> nil.respond_to?(:downcase)
false
>> nil.respond_to?(:downcase!)
false
>> s.respond_to?(:downcase!)
true
>> s.respond_to?(:downcase)
true

Upvotes: 3

Stoic
Stoic

Reputation: 10754

Do not use downcase! as it can return nil if no changes have been made to the string.

Therefore, the correct code will be:

print "Your string = "
input = gets.chomp.downcase

if input.include? "s"
   puts "Go yourself!"
end

Upvotes: 2

Related Questions