Question

I tried running this code in an online IDE supporting Ruby 1.8.7, and the elsif statement isn't being recognized; e.g., if I type in "85", it still returns "Over-Weight".

def prompt
 print ">> "
end

puts "Welcome to the Weight-Calc 3000! Enter your weight below!"

prompt; weight = gets.chomp()

if weight > "300" 
 puts "Over-weight"
elsif weight < "100"
 puts "Under-weight"
end

However when I run the following, it works just fine:

def prompt
 print ">> "
end

puts "Welcome to the Weight-Calc 3000! Enter your weight below!"

prompt; weight = gets.chomp()

if weight > "300" 
 puts "Over-weight"
elsif weight > "100" && weight < "301"
 puts "You're good."
end

Any idea on how I can fix this?

Was it helpful?

Solution

The problem is that you try to compare strings which are evaluated from left to right, not like numbers.

Convert them to integers (or floats), and compare them.

weight = Integer(gets.chomp())

if weight > 300
 puts "Over-weight"
elsif weight < 100
 puts "Under-weight"
end

OTHER TIPS

With

if weight > "300"

you are comparing two strings.

It should be

if weight.to_i > 300
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top