Search code examples
rubystringuser-input

While loop doesn't work. Includes strings and converting to upper case


I couldn't figure out the problem with this code:

select = false
while (!select)
  print "What animal do you want to adopt? (Cat/Dog/Fish): "
  your_animal = gets
  if your_animal.upcase == "CAT" or your_animal.upcase == "DOG" or your_animal.upcase == "FISH"
    puts "Ah, you want #{your_animal}."
    select = true
  else
    puts "Please pick from any of the three animals and make sure it is spelled correctly."
  end
end

The if statement with the three conditions doesn't work, and will execute the code in the else statement even if I write the correct response for the if statement to be activate.

Any help would be appreciated.


Solution

  • Change

    your_animal = gets
    

    to

    your_animal = gets.chomp
    

    The reason is that gets returns the whole string input, including the terminating carriage return.

    Sidenote: instead of

    your_animal.upcase == "CAT" or 
      your_animal.upcase == "DOG" or
      your_animal.upcase == "FISH"
    

    one might use:

    %w(CAT DOG FISH).include? your_animal.upcase