Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby puts string and integer on same line

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

like image 429
catchmikey Avatar asked Dec 04 '22 13:12

catchmikey


1 Answers

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}?
like image 98
Andrew Haines Avatar answered Dec 18 '22 09:12

Andrew Haines