Ruby puts string and integer on same line

catchmikey picture catchmikey · Nov 23, 2012 · Viewed 11.6k times · Source

I just started learning Ruby and uncertain what is causing the error. I'm using ruby 1.9.3

puts 'What is your favorite number?'
fav = gets 
puts 'interesting though what about' + ( fav.to_i + 1 )

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

In my last puts statement, I thought it is a simple combination of a string and calculation. I still do, but just not understanding why this won't work

Answer

Andrew Haines picture Andrew Haines · Nov 23, 2012

In Ruby you can often use "string interpolation" rather that adding ("concatenating") strings together

puts "interesting though what about #{fav.to_i + 1}?"
# => interesting though what about 43?

Basically, anything inside the #{} gets evaluated, converted to a string, and inserted into the containing string. Note that this only works in double-quoted strings. In single-quoted strings you'll get exactly what you put in:

puts 'interesting though what about #{fav.to_i + 1}?'
# => interesting though what about #{fav.to_i + 1}?