Beautiful Multiline Strings in Ruby

This is more of a personal reminder.

You've got a string that needs to have multiple lines and/or have single/double quotes inside. A SQL query or a HTML snippet is a perfect example:

select * from users where status = 'true'

What would you use in Ruby to represent it?

Off the top of my head I would use %{}. Yes, you can create a string like that in case you don't know %{foo}.class #=> String.

The problem is that if you need syntax highlighting, it doesn't look nice on most of the editors (like Sublime Text, VS Code):

Solution

Use heredoc if you need to maintain the original indentation (note the double space preserved in the beginning of line 5):

Use squiggly heredoc (<<~SQL...SQL) - introduced in Ruby 2.3, if you want to remove the indentation:

Replace SQL by whatever language you want to represent (like for instance <<~HTML...HTML) so your editor might know how to highlight it.

Written on June 18, 2021

Share: