所以我正在编写一个程序来建模流程并需要计算费用.逻辑是,如果费用金额小于最小值,则使用最小值,如果费用金额大于最大值则使用最大值.
我当然可以在多行上实现这一点,但有兴趣知道在Ruby中是否有更优雅的方式来实现这一点.
fee_amount = <whatever logic I need>
if fee_amount < min return min
if fee_amount > max return max
return fee_amount
Run Code Online (Sandbox Code Playgroud)
如果你正在寻找一个不那么丑陋(或至少是短暂的)单线:
[min,fee_amount,max].sort[1]
Run Code Online (Sandbox Code Playgroud)
绝对不是Rubyish,因为乍一看发生的事情并不直观.
如果只是一次,我会推荐Shawn Balestracci的答案,这是最美丽的.
另外,以下是我个人图书馆的一些方法:
module Comparable
def at_least other; self < other ? other : self end
def at_most other; self > other ? other : self end
end
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
fee_amount = <whatever logic I need>.at_least(min).at_most(max)
Run Code Online (Sandbox Code Playgroud)
小智 6
Ruby 2.4 添加了Comparable#clamp正是这样做的
fee_amount.clamp(min, max)
Run Code Online (Sandbox Code Playgroud)
https://blog.bigbinary.com/2016/12/13/ruby-2-4-adds-comparable-clamp-method.html
| 归档时间: |
|
| 查看次数: |
1045 次 |
| 最近记录: |