From d5a0b8e3cc48632d0cb99553a7aaf233b22a1eac Mon Sep 17 00:00:00 2001 From: nobu Date: Thu, 11 Aug 2016 07:24:25 +0000 Subject: Comparable#clamp * compar.c (cmp_clamp): Introduce Comparable#clamp. [Feature #10594] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@55863 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- compar.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'compar.c') diff --git a/compar.c b/compar.c index fe0872c4c7..02529c9960 100644 --- a/compar.c +++ b/compar.c @@ -173,6 +173,39 @@ cmp_between(VALUE x, VALUE min, VALUE max) return Qtrue; } +/* + * call-seq: + * obj.clamp(min, max) -> obj + * + * Returns min if obj <=> min is less + * than zero, max if obj <=> max is + * greater than zero and obj 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 Comparable mixin is used by classes whose objects * may be ordered. The class must define the <=> operator, @@ -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); } -- cgit v1.2.3