Read more

Summarizing heredoc in Ruby and Rails

Emanuel
December 08, 2016Software engineer at makandra GmbH

This card tries to summarize by example the different uses of heredoc.

  • In Ruby << vs. <<- vs. <<~
  • In Rails strip_heredoc vs. squish
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

strip_heredoc should be used for a text, where you want to preserve newlines. (multi-line -> multi-line)

squish should be used for a text, where you want to squish newlines. (multi-line -> one-line)

Ruby 2.3+

def foo
  bar = <<~TEXT
    line1
    line2
    line3
  TEXT
  puts bar.inspect
end
foo => "line1\nline2\nline3\n"

Read more: Unindent HEREDOCs in Ruby 2.3

Forms that work in older Rubies

Older forms don't automatically unindent lines:

def foo
  bar = <<TEXT
line1
line2
line3
TEXT
  puts bar.inspect
end
foo => "line1\nline2\nline3\n"
def foo
  bar = <<TEXT
  line1
  line2
  line3
TEXT
  puts bar.inspect
end
foo => "  line1\n  line2\n  line3\n"
def foo
  bar = <<TEXT
    line1
    line2
    line3
  TEXT
  puts bar.inspect
end 
# not valid as alignment of heredoc is wrong
def foo
  bar = <<-TEXT
    line1
    line2
    line3
  TEXT
  puts bar.inspect
end
foo => "    line1\n    line2\n    line3\n"

Read more:

Rails 3+

def foo
  bar = <<-TEXT.strip_heredoc
    line1
    line2
    line3
  TEXT
  puts bar.inspect
end
foo => "line1\nline2\nline3\n"

Read more:

def foo
  bar = <<-TEXT.squish
    line1
    line2
    line3
  TEXT
  puts bar.inspect
end
foo => "line1 line2 line3"

Rails + Ruby 2.3+

def foo
  bar = <<~TEXT.strip
    line1
    line2
    line3
  TEXT
  puts bar.inspect
end
foo => "line1\nline2\nline3"
Emanuel
December 08, 2016Software engineer at makandra GmbH
Posted by Emanuel to makandra dev (2016-12-08 11:23)