Why do two strings separated by space concatenate in Ruby?
In C and C++, string literals next to each other are concatenated. As these languages influenced Ruby, I'd guess it inherits from there.
And it is documented in Ruby now: see this answer and this page in the Ruby repo which states:
Adjacent string literals are automatically concatenated by the interpreter:
"con" "cat" "en" "at" "ion" #=> "concatenation""This string contains "\"no newlines." #=> "This string contains no newlines."
Any combination of adjacent single-quote, double-quote, percent strings will be concatenated as long as a percent-string is not last.
%q{a} 'b' "c" #=> "abc""a" 'b' %q{c} #=> NameError: uninitialized constant q
Implementation details can be found in parse.y
file in Ruby source code. Specifically, here.
A Ruby string
is either a tCHAR
(e.g. ?q
), a string1
(e.g. "q", 'q', or %q{q}), or a recursive definition of the concatenation of string1
and string
itself, which results in string expressions like "foo" "bar"
, 'foo' "bar"
or ?f "oo" 'bar'
being concatenated.