Ruby中的if语句冲突

时间:2012-09-06 18:15:11

标签: ruby if-statement ide ruby-1.8.7 puts

我尝试在支持Ruby 1.8.7的在线IDE中运行此代码,并且elsif语句未被识别;例如,如果我输入“85”,它仍然会返回“超重”。

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

关于我如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:5)

问题在于您尝试比较从左到右评估的字符串,而不是数字。

将它们转换为整数(或浮点数),并进行比较。

weight = Integer(gets.chomp())

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

答案 1 :(得分:5)

使用

if weight > "300"

你正在比较两个字符串。

应该是

if weight.to_i > 300