将值限制为最大值

时间:2012-08-26 15:47:27

标签: ruby math

@a = 200
@b = 1

@c = @a / @b

@c将等于200.如何将@c的最大值设为100?

if @c = 99, do nothing
if @c = 100, do nothing
if @c > 100, make @c 100

在SQL中,这是LEAST函数。

2 个答案:

答案 0 :(得分:7)

Enumerable#min有效:

[@c, 100].min

答案 1 :(得分:-1)

case @c
 when  99
   ##   do something
 when  100
   ##   do something
 else
  @c = 100 if @c > 100 
  # or
  @c = [@c, 100].min # inspired by minitech answer
end