Clamp method was added to Comparable module in Ruby 2.4.

#### Comparable#clamp

The method is used to clamp an object within a specific range of values.

Similarly, strings can also be clamped within a range.

One way to use clamping effectively is to define the minimum and maximum values for the globally used entities in configurations or constants and use them app-wide.

Example,

We have a constant to define range for the score

In order to clamp the input score value within score range we need to do,

#### Comparable#clamp with a Range argument

Comparable#clamp accepts a Range argument with Ruby 2.7

The above score clamping can happen with,

Both numbers and strings can be clamped with a Range argument,

#### Comparable#clamp with a beginless and endless inclusive range(..)

When range is created using .., it runs from the beginning to the end inclusively.

#### Comparable#clamp with a beginless and endless end exclusive range(...)

When range is created with ..., it excludes the end value.

With endless range:

With beginless range: