diff options
Diffstat (limited to 'compar.c')
-rw-r--r-- | compar.c | 34 |
1 files changed, 34 insertions, 0 deletions
@@ -174,6 +174,39 @@ cmp_between(VALUE x, VALUE min, VALUE max) } /* + * call-seq: + * obj.clamp(min, max) -> obj + * + * Returns <i>min</i> if <i>obj</i> <code><=></code> <i>min</i> is less + * than zero, <i>max</i> if <i>obj</i> <code><=></code> <i>max</i> is + * greater than zero and <i>obj</i> otherwise. + * + * 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' + */ + +static VALUE +cmp_clamp(VALUE x, VALUE min, VALUE max) +{ + int c; + + if (cmpint(min, max) > 0) { + rb_raise(rb_eArgError, "min argument must be smaller than max argument"); + } + + c = cmpint(x, min); + if (c == 0) return x; + if (c < 0) return min; + c = cmpint(x, max); + if (c > 0) return max; + return x; +} + +/* * The <code>Comparable</code> mixin is used by classes whose objects * may be ordered. The class must define the <code><=></code> operator, * which compares the receiver against another object, returning -1, 0, @@ -225,4 +258,5 @@ Init_Comparable(void) rb_define_method(rb_mComparable, "<", cmp_lt, 1); rb_define_method(rb_mComparable, "<=", cmp_le, 1); rb_define_method(rb_mComparable, "between?", cmp_between, 2); + rb_define_method(rb_mComparable, "clamp", cmp_clamp, 2); } |