Stefan Stefan - 1 month ago 10
Ruby Question

How to separate a heredoc from other key-value pairs in a hash literal in Ruby?

I just wanted to use a heredoc as a value in a hash literal. While it works fine if the heredoc is the very last element:

{
foo: 123,
bar: <<-HEREDOC
a longer text
HEREDOC
}
#=> {:foo=>123, :bar=>" a longer text\n"}


I couldn't find a way to add another key-value pair after the heredoc. Or, more specifically, I couldn't find a way to insert the separating comma without causing a syntax error:

{
foo: 123,
bar: <<-HEREDOC
a longer text
HEREDOC
# <- causes a syntax error because a comma is missing here, but where to put it?
baz: 456
}

Answer

This seems to work

{
  foo: 123,
  bar: <<-HEREDOC,
    a longer text
  HEREDOC
  baz: 456
}
Comments