Ruby中的if语句冲突

Ruby中的if语句冲突,ruby,if-statement,ide,ruby-1.8.7,puts,Ruby,If Statement,Ide,Ruby 1.8.7,Puts,我尝试在支持Ruby 1.8.7的在线IDE中运行此代码,但无法识别elsif语句;e、 如果我输入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 &l

我尝试在支持Ruby 1.8.7的在线IDE中运行此代码,但无法识别elsif语句;e、 如果我输入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

你知道如何解决这个问题吗?

问题是你试图比较从左到右计算的字符串,而不是数字

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

weight = Integer(gets.chomp())

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

问题是,您试图比较从左到右求值的字符串,而不是数字

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

weight = Integer(gets.chomp())

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

您正在比较两个字符串

应该是

if weight.to_i > 300

您正在比较两个字符串

应该是

if weight.to_i > 300