Are there more elegant ways to prevent negative numbers in Ruby?

后端 未结 5 2138
一向
一向 2021-01-17 23:53

Given that I\'d like to do the following calculation:

total = subtotal - discount

Because discount might be greater than

5条回答
  •  情书的邮戳
    2021-01-18 00:18

    Thinking we can extend the Numeric class?

    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
    

提交回复
热议问题