我对Ruby中的if else循环有疑问。这是代码
print "Enter your age: "
age = gets.chomp.to_i
print "Enter your sex(M/m/F/f) : "
sex = gets.upcase
if (sex == "M" and age > 21)
puts "Hi dude. You may enter."
elsif(sex == "F" and age > 18)
puts "Hi dudette. You may enter."
elsif (sex == "M" and age < 21)
puts "Hi dude. You may not enter."
elsif(sex == "F" and age < 18)
puts "Hi dudette. You may not enter."
else
puts age
puts sex
puts "I do not recognize that sex. Enter only M, m, F, or f."
end
当我输入输入时,无论我输入什么,它只会进入else循环部分。我已经打印出2个变量年龄和性别进行仔细检查,它们符合我列出的条件。那么我的变量存在问题,还是我的if else条件?
答案 0 :(得分:1)
你忘了将chomp添加到性别部分
print "Enter your age: "
age = gets.chomp.to_i
print "Enter your sex(M/m/F/f) : "
sex = gets.chomp.upcase
if (sex == "M" and age > 21)
puts "Hi dude. You may enter."
elsif(sex == "F" and age > 18)
puts "Hi dudette. You may enter."
elsif (sex == "M" and age < 21)
puts "Hi dude. You may not enter."
elsif(sex == "F" and age < 18)
puts "Hi dudette. You may not enter."
else
puts age
puts sex
puts "I do not recognize that sex. Enter only M, m, F, or f."
end
这有效