Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 985
Lukas Avatar asked May 22 '14 15:05

Lukas


People also ask

How do you concatenate strings in Ruby?

Concatenation looks like this: a = "Nice to meet you" b = ", " c = "do you like blueberries?" a + b + c # "Nice to meet you, do you like blueberries?" You can use the + operator to append a string to another. In this case, a + b + c , creates a new string.

How do you add a space when concatenating two strings?

To add two strings we need a '+' operator to create some space between the strings, but when the first string itself has a space with in it, there is no need to assign space explicitly.

What is string interpolation in Ruby?

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.


1 Answers

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 
like image 135
JKillian Avatar answered Oct 12 '22 00:10

JKillian