Why Doesn't This Ruby Case Block Evaluate to True?

Viewed 63

I'm learning case statements for Ruby, and thought this would work, but I am always hitting the else statement. I can never get the input to evaluate as 'true' even when I am passing the input as either 'Cat' or 'Dog'. I did verify that the input type is "String" so I am confused why when I enter 'Cat', when prompted by the gets statement, 'Cat' and 'Cat' in the case block are not setting animal_sound to 'meow'

puts "Give me an animal:"
animal = gets

animal_sound = case animal
  when 'Cat' then 'meow'
  when 'Dog' then 'woof'
  else "I don't know that one, so moooo"
end

puts animal_sound
2 Answers

Sebastian Palma pointed out that the \n that gets adds was causing this to evaluate to false.

Changing case animal to case animal.chomp fixed the problem.

In addition to the other input, which is quite correct, you may wish to use regular expressions rather than strings. This makes it trivial to ignore both whitespace and case.

puts "Give me an animal:"
animal = gets

animal_sound = case animal
  when /^ \s* cat \s* $/ix then 'meow'
  when /^ \s* dog \s* $/ix then 'woof'
  else "I don't know that one, so moooo"
end

puts animal_sound
Related