0

I'm a beginner with Ruby, practicing looping and if statements.

I went a little off track with my course work, and tried to run the following code:

puts("Enter your age!")
age = gets.to_i
again = "Try again!"

while age <= 100 

if age == 0 
  puts("You are very very young. " + again)
  age = gets.to_i

elsif age >= 1 && age <= 5
  puts("You are quite small. Though you are breathing, you may not    understand this. " + again)
  age = gets.to_i
else 
  puts("You are a capable of reading " + again)
  age = gets.to_i
end 
end 
puts("Your age," + age + " is a good one")

When I run it, I am prompted to enter an age. If the age I enter <= 100 everything works according to the code. If not, I get the error:

rehearsal.rb:20:in +': no implicit conversion of Fixnum into String (TypeError) from rehearsal.rb:20:in'

Other StackOverflow answers (solving this error message) I read suggested that the error was in misusing the "to_i" method. I made sure to include it, and my error is still here.

Where is my bug?

1 Answer 1

2

In Ruby, the + method for adding strings doesn't work on integers. In your example, the age variable is an integer. This might seem a little strange if you are used to working with JavaScript.

You need to use string interpolation

puts("Your age, #{age} is a good one")

This works.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked, with an added quotation mark at the end of the line. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.