Why do two strings separated by space concatenate

2020-01-31 02:23发布

问题:

Why does this work in Ruby:

"foo" "bar"
# => "foobar"

I'm unsure as to why the strings were concatenated instead of a syntax error being given.

I'm curious as to whether or not this is expected behavior and whether or not it's something the parser is responsible for wrangling (two strings without operators is considered a single string) or the language definition itself is specifying this behavior (implicit concat).

回答1:

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.



回答2:

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