有没有更优雅的方法来防止 Ruby 中的负数? [英] Are there more elegant ways to prevent negative numbers in Ruby?

查看:53
本文介绍了有没有更优雅的方法来防止 Ruby 中的负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我想做以下计算:

total = subtotal - discount

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

Because discount might be greater than subtotal, there is code like the following:

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 部分或任何类似的代码时,我经常不得不停下来思考.

When seeing the [subtotal - discount, 0].max part or any similar code, I often have to pause and think.

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

Are there more elegant ways to handle this kind of calculation?

推荐答案

我认为您的解决方案本质上是正确的,并且可能是除了小的重构之外最易读的.我可能会像这样稍微改变一下:

I think your solution is essentially correct, and probably the most readable besides a small refactor. I might change it slightly like so:

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

ruby 表达式 [final_total, 0].max 本质上是数学中相同函数的传统解决方案:max {final_total, 0}.区别只是符号和上下文.一旦你看到这个 max 表达式一两次,你可以这样读:final_total,但至少为零".

The ruby expression [final_total, 0].max is essentially the traditional solution in mathematics for the same function: max {final_total, 0}. The difference is just notation and context. Once you see this max expression once or twice you can read it as follows: "final_total, but at least zero".

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

Perhaps if you use this expression more than once you can add another at_least_zero method or something like in Shiko's solution.

这篇关于有没有更优雅的方法来防止 Ruby 中的负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆