【问题标题】:Ruby Ternary If Bug [closed]Ruby 三元 If Bug [关闭]
【发布时间】:2013-10-03 08:11:00
【问题描述】:

如果计数为0>1Pending Quote 如果计数==1 但如果count>1,则我要做的是打印Pending Quotes,输出为2 true,其他两种情况都很好,但我看不到任何明显的东西。

<%= @pending.nil? ? '0' : @pending.count %>
<%= (!@pending.nil? and @pending.count > 1) or (!@pending.nil? and @pending.count == 0) ? 'Pending Quotes' : 'Pending Quote' %>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-2


    【解决方案1】:

    我会使用 pluralize 助手:

    <%= pluralize(@pending, 'Pending Quote') %>
    

    【讨论】:

    • 我一点儿 ROR 都不懂.. 所以我只坚持 Ruby.. :)
    【解决方案2】:

    你必须这样写:

    ((!@pending.nil? and @pending.count > 1) or (!@pending.nil? and @pending.count == 0)) ? 'Pending Quotes' : 'Pending Quote'
    

    你也可以写成

    (!@pending.nil? && (@pending.count > 1 || @pending.count == 0)) ? 'Pending Quotes' : 'Pending Quote'
    

    【讨论】:

    • 啊,现在觉得很傻。谢谢,当我允许时将其标记为接受:)
    • 注意:在 Ruby 中,使用 &amp;&amp; || 表示布尔表达式是惯用的。使用and or 进行流量控制。此外,OP 可能值得注意的是“!x.nil?”通常更适合简单地使用“x”。
    • @tokland 我同意你的看法
    【解决方案3】:

    借助De Morgan...

    @pending.try(:count) == 1 ? 'Pending Quote' : 'Pending Quotes'
    

    【讨论】:

    • 谢谢,这是一种非常巧妙的表达方式
    猜你喜欢
    • 2014-06-30
    • 2016-09-07
    • 2023-04-07
    • 1970-01-01
    • 2017-07-10
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多