Feature #10594 » comparable-clamp.diff
ChangeLog | ||
---|---|---|
Thu Jul 9 18:31:49 2015 Ferdinand Niedermann <nerdinand@nerdinand.com>
|
||
* compar.c (cmp_clamp): Introduce Comparable#clamp [Bug #10594]
|
||
Thu Jul 9 15:07:12 2015 NAKAMURA Usaku <usa@ruby-lang.org>
|
||
* win32/win32.c (waitpid): return immediately if interrupted.
|
compar.c | ||
---|---|---|
return Qtrue;
|
||
}
|
||
/*
|
||
* 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>min</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)
|
||
{
|
||
if (RTEST(cmp_gt(min, max))) {
|
||
rb_raise(rb_eArgError, "min argument must be smaller than max argument");
|
||
}
|
||
if (RTEST(cmp_lt(x, min))) return min;
|
||
if (RTEST(cmp_gt(x, max))) 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,
|
||
... | ... | |
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);
|
||
cmp = rb_intern("<=>");
|
||
}
|
test/ruby/test_comparable.rb | ||
---|---|---|
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 }
|
- « Previous
- 1
- 2
- Next »