2012-09-06 46 views
1

我試圖在支持Ruby 1.8.7的在線IDE中運行此代碼,並且elsif語句未被識別;例如,如果我輸入「85」,它仍會返回「超重」。Ruby中的if語句衝突

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 

然而,當我運行下面的,它工作得很好:

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 

我如何能解決這個問題的任何想法?

回答

5

問題是,您嘗試比較從左到右評估的字符串,而不是數字。

將它們轉換爲整數(或浮點數)並進行比較。

weight = Integer(gets.chomp()) 

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

偉大的技術。謝謝。 –