문제

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 <<?

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top