2015-07-21 2 views
1

Учитывая, что я хотел бы сделать следующий расчет:Есть ли более элегантные способы предотвращения отрицательных чисел в Ruby?

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 часть или любой похожий код, мне часто приходится останавливаться и думать.

Есть ли более элегантные способы обработки такого рода расчетов?

+7

Это довольно элегантно, как это .. – potashin

+2

Наверное, нет. Ваше решение кажется мне очень элегантным. – Adrian

ответ

1

Мысль мы можем расширить класс 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 
0

Простой if заявление может быть проще понять:

def total 
    if discount > subtotal 
    0 
    else 
    subtotal - discount 
    end 
end 
Смежные вопросы