开发者

Ruby decrement to limit

开发者 https://www.devze.com 2023-02-14 09:46 出处:网络
I\'d like to have a set of methods that can increment/decrement a value, but with a lower limit of zero.

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

精彩评论

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