Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method · added in Ruby 4.1

Range#clamp

clamp(min, max) → range
clamp(range) → range

Returns a new Range instance whose begin and end values are clamped to min and max, or to range.begin and range.end.

The returned range excludes its end if any of the following is true:

  • The returned end value is an excluded end value of self or range.

  • Both begin and end values are clamped to the lower bound, or both are clamped to the upper bound. Since self is entirely outside the clamping bounds, the returned range is made empty by excluding its end.

Otherwise, the returned range includes its end.

Examples:

Example
(1..10).clamp(3, 7)       # => 3..7
(1...10).clamp(3, 7)      # => 3..7
(1...10).clamp(3, 10)     # => 3...10
(0...).clamp(0, 10)       # => 0..10

(1..10).clamp(3..7)       # => 3..7
(1..10).clamp(3...7)      # => 3...7
(1..5).clamp(3...7)       # => 3..5

(..10).clamp(3, 7)        # => 3..7
(...10).clamp(3, 7)       # => 3..7
(..10).clamp(3...7)       # => 3...7
(..5).clamp(3...7)        # => 3..5

(1..10).clamp(20..30)     # => 20...20
(1..10).clamp(-10..0)     # => 0...0
(..10).clamp(20..30)      # => 20...20

(1..10).clamp(..7)        # => 1..7
(1..10).clamp(...7)       # => 1...7
(1..5).clamp(...7)        # => 1..5

(1..10).clamp(3..)        # => 3..10
(1..10).clamp(3...)       # => 3..10
(1..).clamp(3..)          # => 3..
(1...).clamp(3...)        # => 3...

Ruby version changes

  1. 4.1