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

时间:2011-11-10 08:40:33

标签: ruby heredoc

我知道我们可以这样做:

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

为什么我想要这个是因为我讨厌这里的单/双引号文件,避免它们会使文件更清晰

任何人都可以提供帮助吗?

谢谢!

4 个答案:

答案 0 :(得分:3)

如果打算执行模板化,也许你真的想要使用ERB。 ERB将支持拆分if / else罚款:

require 'erb'

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

string = template.result(binding)

答案 1 :(得分:2)

我会给出我喜欢的替代方案,即使用分配给变量的heredocs然后插入到主heredoc中,因为它获得了heredoc之外的条件,从而提供了更好的清晰度,你正在寻找(特别是当事情开始变得比一个人为的例子更复杂时):

cond = if true
<<TRUE
yesyesyesyesyesyesyesyesyesyes
TRUE
else
<<NOTTRUE
nonononononononononononononono
NOTTRUE
end.strip

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

如果你正在寻找一个模板,那么那里有很多,而且在我看来比ERB好多了(从看看Haml开始)。

答案 2 :(得分:1)

如果您真的想要这样的话,可以使用ERB

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

答案 3 :(得分:1)

你可以考虑嵌套的heredocs:

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

请注意,您需要将结束}放在行的开头,否则您将有一个额外的空行。

编辑:你可以避免这种情况,也许通过使用一个小辅助函数获得更好的语法:

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
相关问题