如果值超出范围,则返回最小值/最大值的 Ruby 优雅方式 [英] Ruby Elegant Way to Return Min/Max if Value Outside Range
问题描述
所以我正在编写一个程序来为流程建模并需要计算费用.逻辑是,如果费用金额小于最低金额,则使用最低金额,如果费用金额大于最高金额,则使用最高金额.
So I am writing a program to model a process and need to calculate fees. The logic is that if the fee amount is less than a minimum use the minimum and if the fee amount is greater than the maximum use the maximum.
我当然可以在多行上实现这一点,但我很想知道在 Ruby 中是否有更优雅的方法来做到这一点.
I can of course make this happen on multiple lines but would be interested to know if there is a more elegant way to do this in Ruby.
fee_amount = <whatever logic I need>
if fee_amount < min return min
if fee_amount > max return max
return fee_amount
推荐答案
如果只是一个场合,我会推荐 Shawn Balestracci 的答案,这是最漂亮的.
If it is just for one occasion, I would recommend Shawn Balestracci's answer, which is the most beautiful.
或者,以下是我个人库中的一些方法:
Alternatively, here are some methods from my personal library:
module Comparable
def at_least other; self < other ? other : self end
def at_most other; self > other ? other : self end
end
我是这样使用的:
fee_amount = <whatever logic I need>.at_least(min).at_most(max)
这篇关于如果值超出范围,则返回最小值/最大值的 Ruby 优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!