I’m puzzled about why the following happens (I’m using v1.9.3):
s = “[” 9.to_s “]” # error
These other two concatenation constructs appear to work fine:
s = “[” + 9.to_s + “]”
s = “[” << 9.to_s << “]”
What’s the key concept I’m missing here?
Looks like you’re trying to “autoconcatenate” three strings. (If that
wasn’t a word before, it is now!) This works fine IF they’re all
literals, like this:
My SWAG would be that autoconcatenation takes place at the parser
level, and using anything other than a literal would require actual
evaluation, so it can’t be done at that level, only after the thing is
actually evaluated. At that level, though, it breaks the Ruby syntax
rules, which require that you put some kind of operator between items.
That’s why your other examples do work, as you’ve inserted the + or
<< operators.
the thing you are puzzled about happens because you did not tell Ruby
what you want to do with the string “[”. You just placed a number after
it (the error message should have told you, that the parser encountered
a “tInteger” (your 9), but was expecting $end (what means that something
ending the line would be appropriate).
Did your confusion come from string interpolation? It looks somewhat
similar to what you wrote; it would look something like “[#{9.to_s}]”,
where the to_s is fully optional, since everything in between the { and
} will be converted to a string.
You do not need .to_s inside string interpolation. But what is the
point in suggesting that over this solution?
s = “[#{9}]”
sorry for the confusion, robert. i just wanted to show how to combine
auto
or implied concat w another expression (the to_s was just an example
given
by op… could be any method that returns string)…
sorry for the confusion, robert. i just wanted to show how to combine auto
or implied concat w another expression (the to_s was just an example given
by op… could be any method that returns string)…
But the point of string interpolation is that the expression does not need to return a String because #to_s is applied automatically.