I have a whitespace issue with multiline strings.
I have something similar to this in my code where I'm generating some SQL.
def generate_sql
<<-EOQ
UPDATE page
SET view_count = 10;
EOQ
end
But then my SQL indention is all messed up, which I don't really want.
" UPDATE page\n SET view_count = 10;\n"
I could do
def generate_sql
<<-EOQ
UPDATE page
SET view_count = 10;
EOQ
end
Which outputs exactly what I want
"UPDATE page\n SET view_count = 10;\n"
But then my code indention is all messed up, which I don't really want.
Any suggestions on how best to achieve what I'm after?
Ruby 2.3.0 solves this nicely with the squiggly heredoc. Note the difference of the tilde/hyphen between examples.
hyphen_heredoc = <<-MULTILINE_STRING
One line
Second line
Indented two spaces
MULTILINE_STRING
squiggly_heredoc = <<~MULTILINE_STRING_WITH_TILDE
One line
Second line
Indented two spaces
MULTILINE_STRING_WITH_TILDE
2.3.0 :001 > puts hyphen_heredoc
One line
Second line
Indented two spaces
2.3.0 :002 > puts squiggly_heredoc
One line
Second line
Indented two spaces
With the squiggly heredoc, The indentation of the least-indented line will be removed from each line of the content.
There are libraries like ruby-dedent
that let you do
require 'dedent'
def generate_sql
<<-EOQ.dedent
UPDATE page
SET view_count = 10;
EOQ
end
Which results in
"UPDATE page\n SET view_count = 10;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With