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

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

    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
    

    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".

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

提交回复
热议问题