Ruby: How to Write Multi-Line String With No Concatenation

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"

Multiline strings with no indent

In the RubyTapas Episode 249, Avdi Grimm describes a technique to strip leading whitespace from a multi-line string:

def unindent(s)
s.gsub(/^#{s.scan(/^[ \t]+(?=\S)/).min}/, '')
end

It is behavior compatible to other existing solutions to this problem, e.g. String#strip_heredoc in ActiveSupport / Rails or the standalone unindent gem.

You can use this method with a heredoc which is special syntax in ruby (and many other languages) to write multi-line strings.

module Something
def unindent(s)
s.gsub(/^#{s.scan(/^[ \t]+(?=\S)/).min}/, '')
end

def welcome
unindent(<<-TEXT)
Hello

This is an example. This multiline string works
- even with deeper nestings...
All is OK here :)
TEXT
end
end

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.

Creating multiline strings in JavaScript

Update:

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.

A template literal is delimited by backticks:

var html = `
<div>
<span>Some HTML here</span>
</div>
`;

(Note: I'm not advocating to use HTML in strings)

Browser support is OK, but you can use transpilers to be more compatible.


Original ES5 answer:

Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"

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.

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

Does Java have support for multiline strings?

Stephen Colebourne has created a proposal for adding multi-line strings in Java 7.

Also, Groovy already has support for multi-line strings.



Related Topics



Leave a reply



Submit