---
title: "Ruby 2.4 adds Comparable#clamp method"
description:
  "Comparable#clamp method is added to Ruby 2.4 to limit the object to a
  specific range of values"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-4-adds-comparable-clamp-method"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-4-adds-comparable-clamp-method.md"
---

# Ruby 2.4 adds Comparable#clamp method

Comparable#clamp method is added to Ruby 2.4 to limit the object to a specific
range of values

- Author: Abhishek Jain
- Published: December 13, 2016
- Categories: Ruby 2.4, Ruby

In Ruby 2.4,
[clamp method is added to the Comparable module](https://bugs.ruby-lang.org/issues/10594).
This method can be used to clamp an object within a specific range of values.

`clamp` method takes min and max as two arguments to define the range of values
in which the given argument should be clamped.

#### Clamping numbers

`clamp` can be used to keep a number within the range of min, max.

```ruby

10.clamp(5, 20)
=> 10

10.clamp(15, 20)
=> 15

10.clamp(0, 5)
=> 5

```

#### Clamping strings

Similarly, strings can also be clamped within a range.

```ruby

"e".clamp("a", "s")
=> "e"

"e".clamp("f", "s")
=> "f"

"e".clamp("a", "c")
=> "c"

"this".clamp("thief", "thin")
=> "thin"

```

Internally, this method relies on applying the
[spaceship <=> operator](https://en.wikipedia.org/wiki/Three-way_comparison)
between the object and the min & max arguments.

```ruby
if x <=> min < 0, x = min;
if x <=> max > 0 , x = max
else x
```

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-4-adds-comparable-clamp-method)
