代码之家  ›  专栏  ›  技术社区  ›  user3574603

Ruby:如果数字是负数,如何返回正整数或0?[复制]

  •  0
  • user3574603  · 技术社区  · 6 年前

    total = subtotal - discount
    

    因为 discount 可能大于 subtotal

    class Calculator
      def initialize(subtotal: subtotal, discount: discount)
        @subtotal = subtotal
        @discount = discount
      end
    
      def total
        [subtotal - discount, 0].max
      end
    
      private
    
      def subtotal
        @subtotal
      end
    
      def discount
        @discount
      end
    end
    

    当看到 [subtotal - discount, 0].max

    0 回复  |  直到 9 年前
        1
  •  15
  •   Rex Butler    6 年前

    我认为您的解决方案基本上是正确的,而且可能是除了小型重构之外最具可读性的解决方案。我可以稍微改一下:

      def total
        final_total = subtotal - discount
        [final_total, 0].max
      end
    

    ruby表达式 [final_total, 0].max 本质上是同一函数的传统数学解法: max {final_total, 0} . 区别只是符号和上下文。一旦你看到这个max表达式一两次,你可以这样读:“final_total,but least zero”。

    如果您多次使用此表达式,则可以添加另一个表达式 at_least_zero 或者类似于Shiko的解决方案。

        2
  •  2
  •   songyy    9 年前

    我想我们可以扩展 Numeric

    class Numeric                                                                  
      def non_negative                                                             
        self > 0 ? self : 0                                                                      
      end                                                                          
    end                                                                            
    
    class Calculator
      def initialize(subtotal: subtotal, discount: discount)
        @subtotal = subtotal
        @discount = discount
      end
    
      def total
        (@subtotal - @discount).non_negative
      end
    end
    
        3
  •  1
  •   Stefan    9 年前

    平原 if 语句可能更容易理解:

    def total
      if discount > subtotal
        0
      else
        subtotal - discount
      end
    end
    
        4
  •  1
  •   Shiko    6 年前

    为了澄清更多,我们需要添加要扩展的类 核心_外景rb
    1) 创建 归档 配置\初始值设定项 项目中的文件夹。
    2) 粘贴如下@songyy在他的回答中提到的:

    class Numeric                                                                  
      def non_negative                                                             
        self > 0 ? self : 0                                                                      
      end                                                                          
    end    
    

    参考文献:
    https://guides.rubyonrails.org/plugins.html#extending-core-classes