Symbol to string issue
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.
The same behaviour would occur if world
were a number.
"hello" + 1 # Doesn't work in Ruby"hello #{1}" # Works in Ruby
If you want to add a string to something, implement to_str
on it:
irb(main):001:0> o = Object.new=> #<Object:0x134bae0>irb(main):002:0> "hello" + oTypeError: can't convert Object into String from (irb):2:in `+' from (irb):2 from C:/Ruby19/bin/irb:12:in `<main>'irb(main):003:0> def o.to_str() "object" end=> nilirb(main):004:0> "hello" + o=> "helloobject"
to_s
means "You can turn me into a string", while to_str
means "For all intents and purposes, I am a string".