How to restrict an integer to a range in Ruby

ruby

Solution

`Comparable#clamp` is available in Ruby 2.4.

3.clamp(10, 20)
=> 10

27.clamp(10, 20)
=> 20

15.clamp(10, 20)
=> 15

Problem

I have an instance variable `@limit` which must be greater than 0 and no greater than 20. I currently have code like this: ``` @limit = (params[:limit] || 10).to_i @limit = 20 if @limit > 20 @limit = 0 if @limit < 0 ``` This looks ugly. Is there a better way to restrict an integer to a range of values?

Original source