"Have your program add one to the number"?

I’m starting to learn Ruby using the Learn to Program book by Chris
Pine.

On a mini assignment I need to:

"Write a program which asks for a person’s favorite number. Have your
program add one to the number, then suggest the result as a bigger and
better favorite number. (Do be tactful about it, though.) "

Here’s what I have so far…

1 full_name = first_name + ’ ’ + middle_name + ’ ’ + last_name
2 puts full_name + ', ’ + ‘What’s your favorite number???’
3 favorite_number = gets.chomp
4 new_number = favorite_number.to_i + 1
5 puts 'hmmm… What about ’ + new_number + '? ’ + ‘It’s bigger and
better than yours :)’

The program runs smoothly until line 4 than it returns the following
error:

:in `+’: can’t convert Fixnum into String (TypeError)

Could you please point my mistake?

Thanks,
Fellipe

On 19/12/11 14:52, Fellipe de Paula wrote:

:in `+’: can’t convert Fixnum into String (TypeError)

Could you please point my mistake?

You might want to convert “new_number” from an integer into a string
before you add it to the string. :slight_smile: Try adding “.to_s” after
“new_number”.

A number will not automaticly be converted to string. You have to do
it manually (with to_s).

Even better, use string interpolation:

puts “hmmm… Waht about #{new_number}? It’s bigger and better.”

but we are not wanting to add it in string format, we want to say the
number entered was 10 we want to add 1 to it and get 11 as the
new_number

does this not do what one would expect

new_number = favorite_number.to_i + 1

favorite_number.to_i should give us 10 so we can add the 1 integer to it
and get 11

not 101 in a string format, having the same issue.

please advise.

On Dec 18, 2011, at 11:22 PM, Fellipe de Paula wrote:

:in `+’: can’t convert Fixnum into String (TypeError)

Could you please point my mistake?

Are you sure the problem is on line 4? Seems like it is more likely
that it is on line 5 where you try to put new_number into a new message.
That is where you need to convert it back to a string.

Gary W.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs