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

3 回答 3

1

您收到该消息是因为division它是 nil。如果您的条件都不满足,则会显示“我们很抱歉”消息,但不会为division变量分配任何值。

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

puts 'Congratulations! You are '+division+'league.' unless division.nil?
于 2013-04-02T20:28:01.323 回答
1

这是因为您没有进行初始化division,因此它被设置为 nil.Initialize 除法,如下所示:

division = 'in no'

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

于 2013-04-02T20:30:52.373 回答
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已设置,因此它不会返回您看到的错误。

于 2013-04-02T20:54:00.103 回答