ruby-changes:44735
From: mrkn <ko1@a...>
Date: Wed, 16 Nov 2016 13:25:39 +0900 (JST)
Subject: [ruby-changes:44735] mrkn:r56808 (trunk): rational.c: optimize Rational#abs
mrkn 2016-11-16 13:25:33 +0900 (Wed, 16 Nov 2016) New Revision: 56808 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=56808 Log: rational.c: optimize Rational#abs * rational.c (rb_rational_abs): optimize Rational#abs with the specialized implementation. Modified files: trunk/rational.c Index: rational.c =================================================================== --- rational.c (revision 56807) +++ rational.c (revision 56808) @@ -1235,6 +1235,30 @@ nurat_negative_p(VALUE self) https://github.com/ruby/ruby/blob/trunk/rational.c#L1235 return f_boolcast(INT_NEGATIVE_P(dat->num)); } +/* + * call-seq: + * rat.abs -> rat + * rat.magnitude -> rat + * + * Returns the absolute value of +rat+. + * + * (1/2r).abs #=> 1/2r + * (-1/2r).abs #=> 1/2r + * + * Rational#magnitude is an alias of Rational#abs. + */ + +VALUE +rb_rational_abs(VALUE self) +{ + get_dat1(self); + if (INT_NEGATIVE_P(dat->num)) { + VALUE num = rb_int_abs(dat->num); + return nurat_s_canonicalize_internal_no_reduce(CLASS_OF(self), num, dat->den); + } + return self; +} + static VALUE nurat_floor(VALUE self) { @@ -2640,6 +2664,8 @@ Init_Rational(void) https://github.com/ruby/ruby/blob/trunk/rational.c#L2664 #endif rb_define_method(rb_cRational, "positive?", nurat_positive_p, 0); rb_define_method(rb_cRational, "negative?", nurat_negative_p, 0); + rb_define_method(rb_cRational, "abs", rb_rational_abs, 0); + rb_define_method(rb_cRational, "magnitude", rb_rational_abs, 0); rb_define_method(rb_cRational, "floor", nurat_floor_n, -1); rb_define_method(rb_cRational, "ceil", nurat_ceil_n, -1); -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/