Ruby Backslash to Continue String on a New Line

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

Breaking up long strings on multiple lines in Ruby without stripping newlines

Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.

class Subscription
def warning_message
<<~HEREDOC
Subscription expiring soon!
Your free trial will expire in #{days_until_expiration} days.
Please update your billing information.
HEREDOC
end
end

Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

The indentation of the least-indented line will be
removed from each line of the content.

Continuing a statement on the next line WITH A COMMENT

You need to plus sign on the first line. I dont think comments work with the blackslash

puts 'abc' + #Start abc
'def' #Add def

Backslash in Ruby conditional statement

It's a useless line-continuation character.

The question "is it a syntax error" seems pretty simple to discover.

Ruby: Can I write multi-line string with no concatenation?

There are pieces to this answer that helped me get what I needed (easy multi-line concatenation WITHOUT extra whitespace), but since none of the actual answers had it, I'm compiling them here:

str = 'this is a multi-line string'\
' using implicit concatenation'\
' to prevent spare \n\'s'

=> "this is a multi-line string using implicit concatenation to eliminate spare
\\n's"

As a bonus, here's a version using funny HEREDOC syntax (via this link):

p <<END_SQL.gsub(/\s+/, " ").strip
SELECT * FROM users
ORDER BY users.id DESC
END_SQL
# >> "SELECT * FROM users ORDER BY users.id DESC"

The latter would mostly be for situations that required more flexibility in the processing. I personally don't like it, it puts the processing in a weird place w.r.t. the string (i.e., in front of it, but using instance methods that usually come afterward), but it's there. Note that if you are indenting the last END_SQL identifier (which is common, since this is probably inside a function or module), you will need to use the hyphenated syntax (that is, p <<-END_SQL instead of p <<END_SQL). Otherwise, the indenting whitespace causes the identifier to be interpreted as a continuation of the string.

This doesn't save much typing, but it looks nicer than using + signs, to me.

Also (I say in an edit, several years later), if you're using Ruby 2.3+, the operator <<~ is also available, which removes extra indentation from the final string. You should be able to remove the .gsub invocation, in that case (although it might depend on both the starting indentation and your final needs).

EDIT: Adding one more:

p %{
SELECT * FROM users
ORDER BY users.id DESC
}.gsub(/\s+/, " ").strip
# >> "SELECT * FROM users ORDER BY users.id DESC"

How to break the string into two lines in ruby syntax

Ruby will automatically concatenate two strings that are adjacent:

foo = 'a' 'b'
foo # => "ab"

Normally a line-end signifies the end of the assignment:

foo = 'a'
'b'
foo # => "a"

so you can't simply break the lines and expect Ruby to figure out what to do.

\ marks the line as continuing, so you could use:

foo = "a" \
"b"
foo # => "ab"

Or, rely on the + String concatenation:

foo = 'a' +
'b'
foo # => "ab"

I'd probably use the + since it's most often used to join strings already, so its meaning is very obvious. Using \ leads to people joining really long expressions instead of breaking them down.

If your strings are really long, you can use some other tricks:

foo = [
'foo',
'bar'
].join
foo # => "foobar"

If you want to join the strings with a space, such as recombining sentences:

foo = [
'foo',
'bar'
].join(' ')
foo # => "foo bar"

or:

foo = [
'foo',
'bar'
] * ' '
foo # => "foo bar"

Building on all that, I'd use some combination of the above or simply something like:

long_str = 'This is a veeeeeeeryyyyyy' +
' looooonggggg string'
path = "//div/p[contains(., '#{ long_str }')]"

or:

long_str = [
'This is a veeeeeeeryyyyyy',
'looooonggggg string'
].join(' ')
path = "//div/p[contains(., '%s')]" % long_str

Ruby - How to keep \n when I print out strings

i would suggest to use p instead of puts/print:

p "abc\nabc"
=> "abc\nabc"

and in fact with pry you do not need to use any of them, just type your string and enter:

str = "abc\nabc"
=> "abc\nabc"
str
=> "abc\nabc"

Where in the Ruby docs is the line continuation operator (backslash) defined?

https://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html

Ruby programs are sequence of expressions. Each expression are delimited by semicolons(;) or newlines. Backslashes at the end of line does not terminate expression.

https://ruby-doc.org/docs/ruby-doc-bundle/ProgrammingRuby/book/language.html

You can also put a backslash at the end of a line to continue it onto the next.

https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/misc.html

If a line ends with a backslash (\), the linefeed following it is ignored; this allows you to have a single logical line that spans several lines.

https://ruby-doc.org/docs/ruby-doc-bundle/Tutorial/part_02/loops.html

You can make lines "wrap around" by putting a backslash - \ - at the very end of the line.

Why does ruby automatically combine Strings?

Yes. From Literals: String

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

Backslashes in single quoted strings vs. double quoted strings

I'd refer you to "Ruby Programming/Strings" for a very concise yet comprehensive overview of the differences.

From the reference:

puts "Betty's pie shop"

puts 'Betty\'s pie shop'

Because "Betty's" contains an apostrophe, which is the same character as the single quote, in the second line we need to use a backslash to escape the apostrophe so that Ruby understands that the apostrophe is in the string literal instead of marking the end of the string literal. The backslash followed by the single quote is called an escape sequence.



Related Topics



Leave a reply



Submit