Ruby decrement to limit

3.8k Views Asked by At

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's the best "ruby way" to do this?

4

There are 4 best solutions below

3
On BEST ANSWER
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
2
On
def decrement
  @value = [@value-1, 0].max
end
0
On
def decrement(value)
  value -= 1 if value - 1 >= 0
end
0
On
def decrement
  @value -= 1 unless @value - 1 < 0
end