rubystringfixnum

No implicit conversion of Fixnum into String, though "to_i" is used


I'm doing a task in "Learn to Program" by Chris Pine. The program asks for a person's favorite number, adds +1, and shows the result. I wrote this:

puts 'Hello, what\' your favorite number?'
number = gets.to_i
puts 'Here\' a better bigger favorite number - ' + number + 1

And it returned this:

Better_number.rb:3:in \'+\': no implicit conversion of Fixnum into String (TypeError)

I also tried

number = gets.chomp.to_i

but that doesn't seem to work.


Solution

  • You can't add a number to a string in ruby. You have to make it a string.

    puts 'Hello, what\' your favorite number?'
    number = gets.to_i
    puts 'Here\' a better bigger favorite number - ' + (number + 1).to_s
    # or 
    bigger_number = number + 1
    puts 'Here\' a better bigger favorite number - ' + bigger_number.to_s
    # or 
    puts "Here's a better bigger favorite number - #{bigger_number}"