Featured image

Formatting multiline text in code using heredoc is far from unusual in scripting languages. Creating a separate variable just to pass it into a method is redundant in most cases. To avoid this in Ruby, you can use a heredoc directly inside a method call.

You can check the documentation for all usage options. What I especially love about this approach is that you can chain formatting methods directly onto the heredoc and even pass multiple blocks sequentially.

How do you format multiline text? Do you use heredoc in your projects?

execute(
  <<~JSON
    {
      "version": "4.0.9",
      "lang": "Ruby"
    }
  JSON
)

execute(<<~TXT.strip, 'inline text')
  Very
  long
  string
TXT

execute(<<~TXT.gsub(/\s+/, ' ').strip, 'inline text', <<~XML)
  Very
  long
  string
TXT
  <?xml version="1.0" encoding="UTF-8"?>
  <body>
    <version>4.0.9</version>
    <lang>Ruby</lang>
  </body>
XML

def execute(a, b = nil, c = nil)
  puts "a: #{a.inspect}"
  puts "b: #{b.inspect}"
  puts "c: #{c.inspect}"
end