Search code examples
rubystringmultiline

Whitespace with multiline string in ruby


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?


Solution

  • 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.