diff --git a/ChangeLog b/ChangeLog index db63f49a6e..9edcc66d29 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +Thu Aug 11 16:24:23 2016 nerdinand + + * compar.c (cmp_clamp): Introduce Comparable#clamp. [Feature #10594] + Thu Aug 11 03:16:59 2016 Marc-Andre Lafortune * lib/prime.rb: Optimize prime? diff --git a/NEWS b/NEWS index 699344397b..8cfd8b059b 100644 --- a/NEWS +++ b/NEWS @@ -30,6 +30,10 @@ with all sufficient information, see the ChangeLog file or Redmine This is different from Enumerable#sum in that Array#sum doesn't depend on the definition of each method. +* Comparable + + * Comparable#clamp. [Feature #10594] + * Dir * Dir.empty?. [Feature #10121] 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); } diff --git a/test/ruby/test_comparable.rb b/test/ruby/test_comparable.rb index 7624ef2bd3..f35719a9cb 100644 --- a/test/ruby/test_comparable.rb +++ b/test/ruby/test_comparable.rb @@ -76,6 +76,20 @@ class TestComparable < Test::Unit::TestCase assert_equal(true, @o.between?(0, 0)) end + def test_clamp + cmp->(x) do 0 <=> x end + assert_equal(1, @o.clamp(1, 2)) + assert_equal(-1, @o.clamp(-2, -1)) + assert_equal(0, @o.clamp(-1, 3)) + + assert_equal(1, @o.clamp(1, 1)) + assert_equal(0, @o.clamp(0, 0)) + + assert_raise_with_message(ArgumentError, 'min argument must be smaller than max argument') { + @o.clamp(2, 1) + } + end + def test_err assert_raise(ArgumentError) { 1.0 < nil } assert_raise(ArgumentError) { 1.0 < Object.new }