Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use \ instead of + or << to concatenate those strings

I'm using rubocop to basically clean up my messy code...

One of the errors were:

Use \ instead of + or << to concatenate those strings.

Why is this?

I can't find it in the Ruby documentation. Why would I use \ instead of + or <<?

like image 219
BenMorganIO Avatar asked Apr 28 '14 23:04

BenMorganIO


2 Answers

In Ruby, literal strings are allocated as objects in memory when they are encountered. If you concatenate two string literals, as in

str = "foo" + "bar"

you will actually allocate three String objects: "foo", "bar" and the result of the concatenation (which is then referred to by str).

The same happens if you do:

"foo" << "bar"

In many cases, this is only a mild inefficiency which you should not worry too much about.

However, be aware that if you do that in a loop, and if the aggregate String grows large, you will allocate an ever larger String object at every iteration (you can avoid that by collecting the string parts in an Array, and then calling join when you are done; also, foo << 'bar' will modify foo in place, which is acceptable in a loop).

By using \ you do not concatenate intermediate objects, but instead effectively present the parser with one String literal (because \ simply continues the string on the next line).

The "foo" + "bar" + "baz" idiom is frequently used in Java, where strings are immutable, and literals are concatenated at compile time. (Every string literal in Java is only stored once and then reused throughout the code; Ruby does not do that.) Also, Java has no better way to continue strings over multiple lines, which is why Java programmers do it that way.

like image 170
Sigi Avatar answered Nov 15 '22 15:11

Sigi


\ at the end of a line will stop the interpreter from treating the newline as end of statement. Therefore, you can make a multiline string without wearing the cost of concatenation or appending.

like image 21
alex Avatar answered Nov 15 '22 15:11

alex