Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

Why do two strings separated by space concatenate in Ruby?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...