如何使用HEREDOC作为参数传递给方法?

bmp9r5qi  于 2022-09-21  发布在  Ruby
关注(0)|答案(2)|浏览(241)

代码示例:

create_data_with(
  first: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  second: <<~TEXT
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  TEXT,
  third: "Nunc aliquet ipsum at semper sodales."
)

错误出现在以下行中:

second: <<~TEXT

RuboCop是这样描述的:

Lint/Syntax: unterminated string meets end of file
(Using Ruby 3.1 parser; configure using TargetRubyVersion parameter, under AllCops)
      second: <<~TEXT

你能告诉我语法应该是什么吗?我需要保持<<~的外观和使用。

yzuktlbb

yzuktlbb1#

另一种选择是在方法调用之后移动here文档。但是,由于here文档从其标识符后的行开始,因此您的方法调用不能跨越多行:

create_data_with(first: "foo", second: <<~TEXT, third: "bar")
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  TEXT

对于较长的值,您可以使用多个heredoc:

create_data_with(first: <<~FIRST, second: <<~SECOND, third: <<~THIRD)
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  FIRST
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  SECOND
    Nunc aliquet ipsum at semper sodales.
  THIRD
xjreopfe

xjreopfe2#

使用heredocs,解析器期望精确的分隔符关闭文字。您以TEXT打开,但以TEXT,结束,并且Ruby不会将此字面值视为关闭。但是,您可以(在本例中也应该)将逗号放在开始分隔符之后。这里有个解决办法:

create_data_with(
  first: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  second: <<~TEXT,
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  TEXT
  third: "Nunc aliquet ipsum at semper sodales."
)

您甚至可以这样调用方法。例如,波浪形的here文档(<<~TEXT)以前在Rails中作为<<-TEXT.strip_heredoc完成

相关问题