在Ruby中是否有更优雅的方法来防止负数?

Dom*_*mon 3 ruby negative-number

鉴于我想进行以下计算:

total = subtotal - discount
Run Code Online (Sandbox Code Playgroud)

因为discount可能大于subtotal,所以有如下代码:

total = subtotal - discount
Run Code Online (Sandbox Code Playgroud)

当看到[subtotal - discount, 0].max零件或任何类似的代码时,我经常不得不停下来思考。

有没有更优雅的方式来处理这种计算?

Tho*_*lem 7

我认为您的解决方案本质上是正确的,并且除了进行小的重构外,可能是最具可读性的。我可能会像这样稍微更改它:

  def total
    final_total = subtotal - discount
    [final_total, 0].max
  end
Run Code Online (Sandbox Code Playgroud)

[final_total, 0].max对于相同的函数,红宝石表达式本质上是数学上的传统解决方案:max {final_total, 0}。区别只是符号和上下文。一旦看到此最大表达式一次或两次,就可以按以下方式读取它:“ final_total,但至少为零”。

也许如果您多次使用此表达式,则可以添加另一种at_least_zero方法或Shiko解决方案中的类似方法。


son*_*gyy 2

认为我们可以延长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
Run Code Online (Sandbox Code Playgroud)