4

I wrote the basic codes below

puts ' Hi there , what is your favorite number ? '
number = gets.chomp
puts number + ' is beautiful '
puts 1 + number.to_i + 'is way better'

But when I run it,I get the error "String can't be coerced into Fixnum (TypeError)". How do I correct this error please?

theodora nortey
  • 69
  • 1
  • 1
  • 3

4 Answers4

22

You cannot add a String to a number. You can add a number to a String, since it is coerced to a String:

'1' + 1
# => "11"
1 + 1
# => 2
1 + '1'
# TypeError!

Since I suspect you want to show the result of adding 1 to your number, you should explicitly cast it to string:

puts (1 + number.to_i).to_s + ' is way better'

or, use string interpolation:

puts "#{1 + number.to_i} is way better"
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
1

String can't be coerced into Integer usually happens, when you try to add a string to a number. since you want to add 1 to your number and concatenate it with a string "is way better". you have to explicitly cast the result you got from adding 1 to your number to a string and concatenate it with your string "is way better".

you can update your code to this:

puts (1 + number.to_i).to_s + " " + 'is way better'
Yoseph.B
  • 11
  • 2
0

You might find the results of entering 'xyz' as an input surprising.

This discussion for determining if your input string is a number may be helpful.

Community
  • 1
  • 1
Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36
0

Assuming that the numbers are natural numbers:

number = gets.chomp
puts "#{number} is beautiful ", "#{number.succ} is way better"
sawa
  • 165,429
  • 45
  • 277
  • 381