Given that I\'d like to do the following calculation:
total = subtotal - discount
Because discount
might be greater than
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.