Breaking Up Long Strings on Multiple Lines in Ruby Without Stripping Newlines

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.

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"

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

What is the best way to refactor a long string line in ruby?

You can try this

str = "#{envelope_quantity} - envelope #{Budget::util_name(envelope_size)} "\
"#{Budget::util_name(envelope_paper)} #{Budget::util_name(envelope_color)} "\
"#{Budget::util_name(envelope_grammage)} #{Budget::util_name(envelope_model)} "\
"#{Budget::util_name(envelope_print)}"

this way you will be able to confine the string within max line length and also its slightly more readable than using join

Building multi-line strings, programmatically, in Ruby

This would be one way:

code = []
code << "next line of code #{something}"
code << "another line #{some_included_expression}"
code.join("\n")

Extract first line from a (possibly multiline) string

You can use s.split("\n", 2)[0].
This splits the string at each newline and then takes the first element of the array. We also use the limit parameter so it only splits once.

Is there an easy way to do multiline indented strings in Ruby?

Since Ruby 2.3, the <<~ heredoc strips leading content whitespace:

def make_doc(body)
<<~EOF
<html>
<body>
#{body}
</body>
</html>
EOF
end

puts make_doc('hello')

For older Ruby versions, the following is more verbose than the solutions presented in the other answers, but there's almost no performance overhead.
It's about as fast as a single long string literal:

def make_doc(body)
"<html>\n" \
" <body>\n" \
" #{body}\n" \
" </body>\n" \
"</html>"
end

how to break long text to smaller lines by words in ruby/rails?

Rails comes with the word_wrap helper which can split long lines based on a given line width. It always splits at whitespace so long words won't get split / cut.

In rails/console:

lines = helper.word_wrap("a b c d e text longword", line_width: 5)
#=> "a b c\nd e\ntext\nlongword"

puts lines

Output:

a b c
d e
text
longword

Note that it returns a string, not an array.

ruby .split('\n') not splitting on new line

You need .split("\n"). String interpolation is needed to properly interpret the new line, and double quotes are one way to do that.



Related Topics



Leave a reply



Submit