Class: Range

Inherits:
Object show all
Defined in:
lib/mug/clamp.rb

Instance Method Summary collapse

Instance Method Details

#bound(val) ⇒ Comparable

Note:

Numeric#clamp is provided as a polyfill for Ruby < 2.7. On Ruby 2.7+, the built-in Comparable#clamp is used instead.

Bounds val so that first <= new_val <= last.

Returns first when val < first, last when val > last, otherwise val itself.

Raises an exception if val >= end and the range is exclusive.

Examples:

require 'mug/clamp'
(1..10).bound(5)   #=> 5
(1..10).bound(0)   #=> 1
(1..10).bound(11)  #=> 10

Parameters:

  • val (Comparable)

    the value to bound within this range

Returns:

  • (Comparable)

    the bounded value

Raises:

  • (ArgumentError)

    if val >= end and the range is exclusive



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mug/clamp.rb', line 25

def bound val
  a = first
  return a if val < a

  b = last
  if val >= b
    raise ArgumentError, 'greater than or equal to the exclusive range' if exclude_end?
    return b
  end

  val
end