Following code fails
world = :world
result = 'hello' + world
puts result #=> can't co开发者_如何学编程nvert Symbol into String
Following code works
world = :world
result = "hello #{world}"
puts result #=> hello world
Why?
Using ruby 1.8.7
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" + o
TypeError: 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
=> nil
irb(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".
A symbol is not a string, and as such it cannot be concatenated to one without explicit conversion. Try this:
result = 'hello ' + world.to_s
puts result
As a side note, you can always define the method yourself :)
ruby-1.9.2-p0 > class Symbol
ruby-1.9.2-p0 ?> def +(arg)
ruby-1.9.2-p0 ?> [to_s, arg].join(" ")
ruby-1.9.2-p0 ?> end
ruby-1.9.2-p0 ?> end
=> nil
ruby-1.9.2-p0 > :hello + "world"
=> "hello world"
精彩评论