Symbol to string issue

Nick Vanderbilt picture Nick Vanderbilt · Dec 6, 2010 · Viewed 42.5k times · Source

Following code fails

world = :world
result = 'hello' + world
puts result #=> can't convert Symbol into String

Following code works

world = :world
result = "hello #{world}"
puts result #=> hello world

Why?

Using ruby 1.8.7

Answer

mu is too short picture mu is too short · Dec 6, 2010

String interpolation is an implicit to_s call. So, something like this:

result = "hello #{expr}"

is more or less equivalent to this:

result = "hello " + expr.to_s

As karim79 said, a symbol is not a string but symbols do have to_s methods so your interpolation works; your attempt at using + for concatenation doesn't work because there is no implementation of + available that understand a string on the left side and a symbol on the right.