制作最后一个else语句需要什么?

时间:2016-06-18 15:24:35

标签: ruby

如果用户要输入随机字母而不是数字,"这不是数字"应该是输出。相反,它推出了'#34;他们不能进来"我需要改变什么?

print "how old are you? "
age = gets.chomp.to_i

if age >= 21
  puts "They can come in"
elsif age < 21
  puts "they can not come in"
else 
  puts "that is not a number"
end

4 个答案:

答案 0 :(得分:0)

如果您在to_i对象上致电string,您将始终获得0.所以

print "how old are you? "
s_age = gets.chomp
if age.match /\A\d+\Z/
  age = s_age.to_i
  puts "They can come in" if age >= 21
  puts "They can not come in" if age < 21
else
  puts "That is not a number"
end

begin
  print "how old are you? "
  age = Integer gets.chomp # Integer(string) raise an exception if the parameter is not an integer
  puts "They can come in" if age >= 21
  puts "They can not come in" if age < 21
rescue
  puts "That is not a number"
end

答案 1 :(得分:0)

我实际上会事先检查它是否是有效数字。你的逻辑是有缺陷的,就像他们输入字母一样,然后gets.chomp.to_i只返回0,这在技术上小于21。实际上,根据您想要的限制,立即转换为整数是非常安全的。所以,这样做:

age = gets.chomp.to_i
if age == 0 then puts "that is not a number" end

然后是你的其余代码。 并非此解决方案不适用于有效的“0岁”答案,因为0默认为无效。

答案 2 :(得分:0)

print "How old are you? "
puts Integer(gets) >= 21 ? 'They can come in' : 'They can not come in' rescue puts 'Not a number'

答案 3 :(得分:0)

我能看到的最简单的方法是对elsif条件稍加修改:

print "how old are you? "
age = gets.chomp.to_i

if age >= 21
  puts "They can come in"
elsif age >= 0 && age < 21
  puts "they can not come in"
else 
  puts "that is not a number"
end