Reputation: 1
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
The error I get is this:
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>'
Upvotes: 0
Views: 86
Reputation: 1220
This is because you're not initializing division
, and it's thus set to nil.Initialize division like this:
division = 'in no'
Do that either in else block or before the first if.
Upvotes: 1
Reputation: 160551
Just to show how your code can be more Ruby-like:
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
I'm sure it could be tighter, but this is how I'd do it. Also, because the code checks to see if division
is set, it won't return the error you're seeing.
Upvotes: 0
Reputation: 11436
You're getting that message because division
is nil. In the case that none of your conditions are met the 'We are sorry' message is displayed, but no value is assigned to the division
variable.
You can get rid of it by doing:
puts 'Congratulations! You are '+division+'league.' unless division.nil?
Upvotes: 1