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

后端 未结 5 2081
一向
一向 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:15

    Just to clarify more, we need to add classes to be extended in core_ext.rb . file :
    1) Create core_ext.rb file under config\initializers folder in your project.
    2) Paste below as mentioned by @songyy in his answer:

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

    Reference:
    https://guides.rubyonrails.org/plugins.html#extending-core-classes

提交回复
热议问题