Ruby 可以在here文档中放置条件语句吗?

Ruby 可以在here文档中放置条件语句吗?,ruby,heredoc,Ruby,Heredoc,我知道我们可以这样做: puts <<START ----Some documents #{if true "yesyesyesyesyesyesyesyesyesyes" else "nonononononononononononononono" end} ----Some documents START puts <<START ----Some documents #{if true} yesyesyesyesyesyesyesyesyesyes #{else}

我知道我们可以这样做:

puts <<START
----Some documents
#{if true
"yesyesyesyesyesyesyesyesyesyes"
else
"nonononononononononononononono"
end}
----Some documents
START
puts <<START
----Some documents
#{if true}
yesyesyesyesyesyesyesyesyesyes
#{else}
nonononononononononononononono
#{end}
----Some documents
START
put如果您真的想要这样的东西,您可以使用:

str = <<-ERB
----Some documents
<% if true %>
yesyesyesyesyesyesyesyesyesyes
<% else %>
nonononononononononononononono
<% end %>
----Some documents
ERB
erb = ERB.new(str, nil, '<>');
puts erb.result(binding)

str=如果您的目的是执行模板化,那么您可能实际上想要使用ERB。雇员再培训局将支持拆分if/else罚款:

require 'erb'

template = ERB.new <<-DOC
----Some documents
<% if true %>
yesyesyesyesyesyesyesyesyesyes
<% else %>
nonononononononononononononono
<% end %>
----Some documents
DOC

string = template.result(binding)
需要“erb”

模板= Eb.NeX

可以考虑嵌套遗传:

puts <<EOF
---- Some documents
#{if true; <<WHENTRUE
yesyesyes
WHENTRUE
else <<WHENFALSE
nonono
WHENFALSE
end
}---- Some documents
EOF

我会给出我喜欢的另一种选择,那就是使用分配给变量的herdoc,然后插入到主herdoc中,因为它在herdoc之外获得条件,从而提供您想要的更好的清晰度(特别是当事情开始变得比人为的例子更复杂时):

cond=如果为真
def if_text(condition, whentrue, whenfalse)
  (condition ? whentrue : whenfalse).chomp
end

puts <<EOF
---- Some documents
#{if_text(true, <<ELSE, <<ENDIF)
yesyesyes
ELSE
nonono
ENDIF
}
---- Some documents
EOF
cond = if true
<<TRUE
yesyesyesyesyesyesyesyesyesyes
TRUE
else
<<NOTTRUE
nonononononononononononononono
NOTTRUE
end.strip

puts <<START
----Some documents
#{cond}
----Some documents
START