开发者

Ruby decrement to limit

I'd like to have a set of methods that can increment/decrement a value, but with a lower limit of zero.

Basically:

def decrement
  @value -= 1
end

Except, I don't want it to go lower than zero.

What'开发者_JAVA百科s the best "ruby way" to do this?


def decrement
  @value -= 1 unless @value.zero?
end

Or if you'd like to throw an exception:

def decrement
  raise RangeError, "can't decrement below zero" if @value.zero?
  @value -= 1
end


def decrement
  @value = [@value-1, 0].max
end


def decrement(value)
  value -= 1 if value - 1 >= 0
end


def decrement
  @value -= 1 unless @value - 1 < 0
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜