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).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With