【问题标题】:What does the Ruby operator == do in this case?在这种情况下,Ruby 运算符 == 做了什么?
【发布时间】:2013-01-23 06:38:31
【问题描述】:

我目前正在查看piece of code from the excellent Rails-composer,但我不明白第 3 行中的 Embedded Ruby 做了什么:

<% flash.each do |name, msg| %>
  <% if msg.is_a?(String) %>
    <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
      <a class="close" data-dismiss="alert">&#215;</a>
      <%= content_tag :div, msg, :id => "flash_#{name}" %>
    </div>
  <% end %>
<% end %>

到目前为止,我已经查看了Ruby documentation,但没有运气。一旦我了解了这段代码的工作原理,我想扩展它以支持所有级别的flash[] 消息。

【问题讨论】:

标签: ruby


【解决方案1】:

这是Ternary Operator

(condition) ? "true value" : "false value"

如果name == :notice 使用"success" 否则"error"

【讨论】:

  • 维基百科的链接无法正常工作,因此请将 URL 中的 ? 替换为 %3F
【解决方案2】:

这一行

result = (name == :notice ? "success" : "error")

可以翻译成:

result =""
if(name == :notice)
{
 result = "success"
}
else
{
 result = "error"
}

在您的情况下,结果不是变量,但它的值被粘贴到 html。

编辑

我想扩展它以支持所有级别的 flash[] 消息。

这个运算符通常只用于简单的真假条件,但如果你真的想要你可以这样使用它:

name == :notice ? "success" : name == :error ? "error" : "something else"

考虑改用这个(更具可读性)

if name == :notice
 "success"
elsif name == :error
 "error"
else
 "something else"
end

【讨论】:

  • 嗨@gisek,我希望我能知道我的问题的2个答案。真的很感谢你。
  • @FrancisOuellet 我很高兴能帮上忙 :)
【解决方案3】:

该代码会动态更改 div 类。它检查 :notice 并且 div 类将获得:

  • “警报警报成功”
  • “警报警报错误”

取决于:通知结果。

【讨论】:

    【解决方案4】:

    它正在显示闪存的内容。 flash的每个键值对都显示为一个单独的div,div的类取决于key。

    第 3 行根据键是否为 :notice 添加了一个 alert-success 或 alert-failure 类

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2017-12-24
      • 1970-01-01
      相关资源
      最近更新 更多