How to break the string into two lines in ruby syntax

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

Id probably use the + since its 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, Id 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

You can use a backward slash to indicate the string continues on the next line, like so:

str = this is a long 
string

print str # => this is a long string

If your string gets way too big, it might be a good idea to use here docs instead. They allow you to write pieces of text in the middle of the code:

str = <<HEREDOC
This is my string :)
Lets imbue code in the imbued doc: #{[4, 2, 3, 1].sort}
HEREDOC

print str
# => This is my string :)
# => Lets imbue code in the imbued doc: [1, 2, 3, 4]

HEREDOC can be any name you want to give it. You can learn more about here docs here.

How to break the string into two lines in ruby syntax

Leave a Reply

Your email address will not be published. Required fields are marked *