Beautiful Multiline Strings in Ruby
2 min readJun 18, 2021
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):
The solution is:
- use heredoc if you need to maintain the original indentation (note the double space preserved in the beginning of line 5):
- use squiggly heredoc (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.