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
A string (or word) over Σ is any finite sequence of symbols from Σ. For example, if Σ = {0, 1}, then 01011 is a string over Σ. The length of a string s is the number of symbols in s (the length of the sequence) and can be any non-negative integer; it is often denoted as |s|.
Converting between symbols to strings is easy - use the . to_s method. Converting string to symbols is equally easy - use the . to_sym method.
A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value. Mutability is the ability for an object to change.
The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string. Normally, you will not use it in your own code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With