Ruby 我能';“我不明白为什么我会出错”;can';t将nil转换为字符串";

Ruby 我能';“我不明白为什么我会出错”;can';t将nil转换为字符串";,ruby,Ruby,我得到的错误是: puts 'Please enter your age ' age=gets.chomp age=age.to_i if age >=18 division='in the adult ' elsif age >=12 division='in the junior ' elsif age >=5 division='in the novice ' else puts 'We are sorry, but you are ineligible

我得到的错误是:

puts 'Please enter your age '
age=gets.chomp
age=age.to_i

if  age >=18
division='in the adult '

elsif age >=12
division='in the junior '

elsif age >=5
division='in the novice '

else    
puts 'We are sorry, but you are ineligible to play in the league at this time.'

end
puts 'Congratulations! You are '+division+'league.'

sleep 5
很抱歉,您现在没有资格参加联盟比赛。
:18:在“+”中:无法将nil转换为字符串(TypeError)
:18:in`'

您收到该消息是因为
部门
为零。如果您的任何条件都不满足,则会显示“We's sorry”(我们很抱歉)消息,但不会为
division
变量赋值

您可以通过执行以下操作来摆脱它:

We are sorry, but you are ineligible to play in the league at this time.
:18:in `+': can't convert nil into String (TypeError)
:18:in `<main>'

这是因为您没有初始化分区,因此它被设置为零。初始化分区如下:

puts 'Congratulations! You are '+division+'league.' unless division.nil?

在else块中或在第一个if之前执行此操作。

只是为了展示您的代码如何更像Ruby:

division = 'in no'

我肯定会更紧,但我会这样做。此外,由于代码检查是否设置了
除法
,因此不会返回您看到的错误。

对不起。如果输入4或更少,我只会得到错误。非常感谢。我正在使用的文本中没有出现类似的内容。正如@Still a kid在他的回答中提到的,您最好先为
除法设置一个值。我如何初始化除法?我已经编辑了我的答案。但最好遵循理查德·布朗的答案,即使用unlessWow!好吧,我只是试着用case做同样的事情,我的看起来不像你的那么整洁。谢谢你的洞察力。
print 'Please enter your age: '
age = gets.chomp.to_i

division = case 
          when age >= 18
            'adult'

          when age >= 12
            'junior'

          when age >=5
            'novice' 

          else    
            nil

          end

if division
  puts "Congratulations! You are in the #{ division } league."
else
  puts 'We are sorry, but you are ineligible to play in the league at this time.'
end