문제

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?

도움이 되었습니까?

해결책

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

다른 팁

With

if weight > "300"

you are comparing two strings.

It should be

if weight.to_i > 300
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top