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
精彩评论