| .. | ||
| mrblib | ||
| test | ||
| mrbgem.rake | ||
| README.md | ||
mruby-compar-ext
Comparable module extension.
This mrbgem adds the clamp method to the Comparable module.
Comparable#clamp
The clamp method restricts a value to a given range.
Syntax:
obj.clamp(min, max) -> obj
obj.clamp(range) -> obj
Description:
- In the
(min, max)form, it returns:minifobj <=> minis less than zero.maxifobj <=> maxis greater than zero.objotherwise.
- In the
(range)form, it returns:range.beginifobj <=> range.beginis less than zero.range.endifobj <=> range.endis greater than zero (andrange.endis notniland the range is inclusive).objotherwise.
- If
range.beginisnil, it is considered smaller thanobj. - If
range.endisnil, it is considered greater thanobj.
Examples:
# Using min and max arguments
12.clamp(0, 100) #=> 12
523.clamp(0, 100) #=> 100
-3.123.clamp(0, 100) #=> 0
'd'.clamp('a', 'f') #=> 'd'
'z'.clamp('a', 'f') #=> 'f'
# Using a Range argument
12.clamp(0..100) #=> 12
523.clamp(0..100) #=> 100
-3.123.clamp(0..100) #=> 0
'd'.clamp('a'..'f') #=> 'd'
'z'.clamp('a'..'f') #=> 'f'
# Using ranges with nil begin or end
-20.clamp(0..) #=> 0
523.clamp(..100) #=> 100
Error Handling:
- Raises an
ArgumentErrorif an exclusive range (e.g.,0...100) is provided as therangeargument whenrange.endis notnil. - Raises an
ArgumentErrorifminandmaxarguments cannot be compared (e.g., aStringand anInteger). - Raises an
ArgumentErrorif theminargument is greater than themaxargument.
100.clamp(0...100) # ArgumentError: cannot clamp with an exclusive range
10.clamp("a", "z") # ArgumentError: comparison of String with String failed (depending on mruby version, may also be other errors if types are incompatible)
100.clamp(10, 0) # ArgumentError: min argument must be smaller than max argument