Do adjacent strings or strings separated by backslash and a newline
create multiple String objects?
For example:
s1 = ‘asdf’ ‘qwer’
s2 = ‘asdf’
‘qwer’
I don’t know how to figure this out, but I ran benchmarks and compared
against ‘<<’ and ‘+’ and it looks like each example above only creates
a single String object. What’s really happening?
I don’t know how to figure this out, but I ran benchmarks and compared
against ‘<<’ and ‘+’ and it looks like each example above only creates
a single String object. What’s really happening?
-pachl
The string concatenation method is “+”
s1 = “asdf” + “qwer”
This creates 3 string objects, “asdf”, “qwer”, and “asdfqwer”.
Anyway, going off your reply, how many strings does the following
create?
s1 = ‘asdf’ ‘qwer’
Son-of-a-gun! Ruby does concatenate adjacent string literals. I learn
something every day.
My new copy of The_Ruby_Programming_Language says that Ruby
concatenates adjacent string literals during the parsing process. That
makes me think that there’s only 1 string created, “asdfqwer”.
s1 = ‘asdf’ ‘qwer’ s2 # this one errs, ruby expect all literals
s1 = ‘asdf’ ‘qwer’ + s2
from :0
s1 = (‘asdf’ ‘qwer’) + s2
#=> “asdfqwerasdfqwer”
Thanks everyone. This answered my question. It makes total sense that
the parser would take care of this adjacent string concatenation.
I was creating long SQL strings and to make the code readable, I was
splitting the query string among multiple lines and joining them using
the ‘<<’ operator.
sql = 'select * from table ’ <<
'where id=3 ’ <<
‘order by id’
Now I can go refactor my code and avoid the unnecessary overhead of
string appending/concatenating.
Do adjacent strings or strings separated by backslash and a newline
create multiple String objects?
iianm, no. you create just one string literal, ergo one string object.
it’s part of ruby syntax on string literals. very useful if you want
to emphasize a string part, similar to numeric literals where you can
put underscore to separate some digits…