Heredocs and leading spaces in Ruby

I gave this little tutorial to @dylangrafmyre this morning and wanted to share it.

Net of the story is that while you can trim leading spaces in heredocs in Ruby, it’s probably best just to put the text flush left unless you have something like SQL where leading spaces and a trailing \n don’t matter.

This is fun to try in IRB.

(Note, for some reason you can’t paste the multi-line heredoc into Pry).

Dash before the TXT

The dash allows the closing TXT to not be flush with the left edge of the screen. If you take away the dash, you have to write the example like this

      str = <<TXT
        Updated Record 1
        changed home_street1 to XXXXXX
        changed home_city to XXXXXX
TXT 

With the dash, the closing TXT does not have to be flush with the left edge of the screen.

      str = <<TXT
        Updated Record 1
        changed home_street1 to XXXXXX
        changed home_city to XXXXXX
      TXT 

Leading spaces

In this case, str will have leading space at the beginning of each line, and an return at the very end.

      str = <<-TXT
        Updated Record 1
        changed home_street1 to XXXXXX
        changed home_city to XXXXXX
      TXT 

Fixing with gsub

In this case, str will have leading space at the beginning of each line, and an return at the very end.

      str = <<-TXT.gsub(/^ +/, "")
        Updated Record 1
        changed home_street1 to XXXXXX
        changed home_city to XXXXXX
      TXT

Fixing with gsub

In this case, str will have leading space at the beginning of each line, and an return at the very end.

      str = <<-TXT.gsub(/^ +/, "")
        Updated Record 1
        changed home_street1 to XXXXXX
        changed home_city to XXXXXX
      TXT

Getting rid of the trailing new line

      str = <<-TXT.gsub(/^ +/, "").strip
        Updated Record 1
        changed home_street1 to XXXXXX
        changed home_city to XXXXXX
      TXT

Doing the above using split, map, strip, join

This is a good exercise in seeing how the enumerable and string methods work:

      str = <<-TXT.split("\n").map(&:strip).join("\n")
        Updated Record 1
        changed home_street1 to XXXXXX
        changed home_city to XXXXXX
      TXT