您可以在此处文档中放置条件语句吗?

发布于 2024-10-05 14:15:09 字数 153 浏览 3 评论 0原文

您可以在此处文档中放置条件语句吗?

即:

sky = 1
str = <<EOF
The sky is #{if sky == 1 then blue else green end}
EOF

谢谢

Can you put a conditional statement inside a here-doc?

IE:

sky = 1
str = <<EOF
The sky is #{if sky == 1 then blue else green end}
EOF

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

油饼 2024-10-12 14:15:09

是的,你可以。 (你尝试过吗?)正如你所做的那样声明的 HEREDOC 的行为就像一个双引号字符串。如果您碰巧想要相反,您可以单引号您的 HEREDOC 指示符,如下所示:

str = <<EOF
  #{ "this is interpolated Ruby code" }
EOF

str = <<'EOF'
  #{ This is literal text }
EOF

示例中的“绿色”和“蓝色”是错误的,除非您有具有这些名称的方法或局部变量。您可能想要:

str = <<EOF
  The sky is #{if sky==1 then 'blue' else 'green' end}
EOF

...或简洁版本:

str = <<EOF
  The sky is #{sky==1 ? :blue : :green}
end

与所有字符串插值一样,每个表达式的结果都调用了 #to_s 。由于符号的字符串表示形式是相同的文本,因此在插值中使用符号可以在键入时节省一个字符。我最常使用它,例如:

cats = 13
str = "I have #{cats} cat#{:s if cats!=1}"

Yes, you can. (Did you try it?) HEREDOCs declared as you did act like a double-quoted string. If you happened to want the reverse, you would single-quote your HEREDOC indicator like so:

str = <<EOF
  #{ "this is interpolated Ruby code" }
EOF

str = <<'EOF'
  #{ This is literal text }
EOF

The "green" and "blue" in your example are wrong, unless you have methods or local variables with those names. You probably wanted either:

str = <<EOF
  The sky is #{if sky==1 then 'blue' else 'green' end}
EOF

...or the terser version:

str = <<EOF
  The sky is #{sky==1 ? :blue : :green}
end

As with all string interpolation, the result of each expression has #to_s called on it. As the string representation of a symbol is the same text, using symbols in interpolation like that saves one character when typing. I use it most often like:

cats = 13
str = "I have #{cats} cat#{:s if cats!=1}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文