Gar*_*ant 1 ruby ide if-statement puts ruby-1.8.7
我尝试在支持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
Run Code Online (Sandbox Code Playgroud)
但是,当我运行以下操作时,它可以正常工作:
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
Run Code Online (Sandbox Code Playgroud)
关于如何解决这个问题的任何想法?
问题是你试图比较从左到右评估的字符串,而不是数字.
将它们转换为整数(或浮点数),并进行比较.
weight = Integer(gets.chomp())
if weight > 300
puts "Over-weight"
elsif weight < 100
puts "Under-weight"
end
Run Code Online (Sandbox Code Playgroud)
同
if weight > "300"
Run Code Online (Sandbox Code Playgroud)
你正在比较两个字符串.
它应该是
if weight.to_i > 300
Run Code Online (Sandbox Code Playgroud)