Reputation: 143
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?
Upvotes: 1
Views: 267
Reputation: 2635
With
if weight > "300"
you are comparing two strings.
It should be
if weight.to_i > 300
Upvotes: 5
Reputation: 13925
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
Upvotes: 5