如何在 Ruby 的散列文字中将 heredoc 与其他键值对分开?

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

我只是想使用 heredoc 作为散列文字中的值。如果 heredoc 是最后一个元素,它工作正常:

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

我找不到添加另一个键值对的方法 heredoc 之后。或者,更具体地说,我找不到在不引起语法错误的情况下插入分隔逗号的方法:

{
  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
}

这似乎有效

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

是正确的。 为什么 这样做的原因是 heredoc 不会在开始标识符之后立即开始,而是在 跟随 开始标识符的行上。开始标识符(在同一行)之后的所有内容都照常解析。

这不仅允许您将 , 紧跟在 <<-HEREDOC 之后,还允许您在一行中定义整个散列:

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

您还可以传递两个 heredoc:(使用 ~ 而不是 - 去除空格)

{ foo: 123, bar: <<~BAR, baz: <<~BAZ }
  bar's value
BAR
  baz's value
BAZ
#=> {:foo=>123, :bar=>"bar's value\n", :baz=>"baz's value\n"}

Ruby 的 heredoc documentation 包含类似的示例,但不幸的是 RDoc 没有正确处理,因此它们经常被忽略:

To call a method on a heredoc place it after the opening identifier:

expected_result = <<-EXPECTED.chomp
One plus one is #{1 + 1}  
EXPECTED

You may open multiple heredocs on the same line, but this can be difficult to read:

 puts(<<-ONE, <<-TWO)
 content for heredoc one
 ONE
 content for
 heredoc two
 TWO