Posted about 2 years ago. Visible to the public. Repeats.

Summarizing heredoc in ruby and rails

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

  • In Ruby << vs. <<- vs. <<~
  • In Rails strip_heredoc vs. squish

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

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

Read more:

Ruby 2.3+

Copy
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

Rails 3+

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

Read more:

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

Rails + Ruby 2.3+

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

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Emanuel De
Last edit:
over 1 year ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more