我无法弄清楚为什么我收到错误“无法将nil转换为String”

时间:2013-04-02 20:25:34

标签: 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 to play in the league at this time.'

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

sleep 5

我得到的错误是:

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>'

3 个答案:

答案 0 :(得分:1)

您收到该消息是因为division为零。如果您的条件均未满足,则会显示“我们很抱歉”消息,但没有为division变量分配值。

您可以通过以下方式摆脱它:

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

答案 1 :(得分:1)

这是因为你没有初始化division,因此设置为nil.Initialize division就像这样:

division = 'in no'

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

答案 2 :(得分:0)

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

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

我确信它可能更紧,但这就是我要做的。此外,因为代码会检查是否设置了division,所以它不会返回您看到的错误。