Alex Marvick Alex Marvick - 1 year ago 59
Ruby Question

While loop in Ruby isn't working. Includes strings and converting to upper case

I'm still new to Ruby Programming, and I've done basic programming concepts in other languages before so I just need to adapt to the correct syntax. I couldn't figure out the problem with this code, however, the 'if' statement with the three conditions isn't working and will always execute the code in the 'else' statement, even if you write the correct response for the 'if' statement to activate. See below:

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
puts "Please pick from any of the three animals and make sure it is spelled correctly."

Any help would be appreciated. Thank you!

Answer Source


your_animal = gets


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download