Ruby优雅方式返回最小值/最大值,如果值超出范围

tho*_*mas 2 ruby

所以我正在编写一个程序来建模流程并需要计算费用.逻辑是,如果费用金额小于最小值,则使用最小值,如果费用金额大于最大值则使用最大值.

我当然可以在多行上实现这一点,但有兴趣知道在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)

Sha*_*cci 9

如果你正在寻找一个不那么丑陋(或至少是短暂的)单线:

[min,fee_amount,max].sort[1]
Run Code Online (Sandbox Code Playgroud)

绝对不是Rubyish,因为乍一看发生的事情并不直观.

  • 它是_clever_,但是_not beautiful_.这是表达所需结果的非常方面的方式,我希望永远不会在生产代码中遇到它,除非它是一个方法的一行实现,其名称告诉我它的作用. (2认同)

saw*_*awa 6

如果只是一次,我会推荐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)