2012-09-06 3 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

숫자가 아닌 왼쪽에서 오른쪽으로 평가되는 문자열을 비교하려고하면 문제가 생깁니다.

정수 또는 부동 소수점으로 변환하여 비교하십시오.

if weight > "300" 

weight = Integer(gets.chomp()) 

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

다양한 기술해야한다. 감사. –