Search code examples
ruby

Downcasing user input makes gsub() prone to errors


I have discovered a bug that occurs when downcase() and gsub() are run in concert. The following code works just fine as long as the user input contains at least one capital letter. However, when run with input that contains no capital letters, I get the error "undefined method `include?' for nil:NilClass"

print("Favorite Animal: ")
animal = gets.chomp().downcase!
if animal.include?("cat")
  animal.gsub!(/cat/, "dog")
end
print("Your favorite animal: #{animal}")

Solution

  • From the fine manual:

    downcase!(*options) → self or nil
    Downcases the characters in self; returns self if any changes were made, nil otherwise:

    So if there was nothing to downcase, #downcase! returns nil as documented.

    You want to use #downcase instead of #downcase!:

    animal = gets.chomp().downcase
    

    so that animal get the downcased string.