Ruby backslash to continue string on a new line?

That is valid code.

The backslash is a line continuation. Your code has two quoted runs of text; the runs appear like two strings, but are really just one string because Ruby concatenates whitespace-separated runs.

Example of three quoted runs of text that are really just one string:

"a" "b" "c"
=> "abc"

Example of three quoted runs of text that are really just one string, using \ line continuations:

"a" \
"b" \
"c"
=> "abc"

Example of three strings, using + line continuations and also concatenations:

"a" +
"b" +
"c"
=> "abc"

Other line continuation details: "Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, -, or backslash at the end of a line, they indicate the continuation of a statement." - Ruby Quick Guide


The backslash character does not concatenate any strings. It prevents the line-break from meaning that those two lines are different statements. Think of the backslash as the opposite of the semicolon. The semicolon lets two statements occupy one line; the backslash lets one statement occupy two lines.

What you are not realizing is that a string literal can be written as multiple successive literals. This is legal Ruby:

s = "A string of Ruby that" "continues on the same line"
puts s

Since that is legal, it is legal to put a line break between the two string literals - but then you need the backslash, the line-continuation character, to tell Ruby that these are in fact the same statement, spread over two lines.

s = "A string of Ruby that" \
"continues on the same line"
puts s

If you omit the backslash, it is still legal, but doesn't give the result you might be hoping for; the string literal on the second line is simply thrown away.

Tags:

Ruby