2011-11-10 8 views
1

私たちはこのようなことを行うことができます知っている:ここにドキュメントの中に条件文を入れることができますか?

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 

私はここに、文書内の単一/二重引用符を嫌うので、これは欲しい理由、それらを避けることは、文書をより明確にするでしょう

誰でも助けることができますか?

ありがとうございました!

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

答えて

2

は、たぶん、あなたが実際に意図はテンプレートを実行する場合ERBを使用する:あなたは本当にそのようなことを望んでいた場合

+0

ありがとう、それは助けます!特に新入生がルビーのために。 – aaron

0

あなたは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

あなたは、ネストされたヒアドキュメント考えることができます:

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 
1

私はに割り当てられヒアドキュメントを使用することである、私が有利に働く選択肢をあげますそれは、このようにあなたが探しているより明確に与え、ヒアドキュメントの条件付きの外を取得して、その後、マスター・ヒアドキュメントに挿入されている変数(場合は特に、物事不自然な例よりも複雑な取得を開始):

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

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

あなたがテンプレートを探しているなら、そこにはたくさんのものがあり、私の意見では、ERBよりも十分に優れています(Hamlを見ることから始めます)。

+0

ありがとう、私はハムルを見ます – aaron

関連する問題