summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKenta Murata <mrkn@mrkn.jp>2020-01-17 10:47:20 +0900
committerKenta Murata <mrkn@mrkn.jp>2020-01-17 10:57:51 +0900
commit5275d8bf4c43db9f057d24a26cf33ecd69f8b345 (patch)
treed77ff868dc4a32a0f8e8e5e56b3b03aca527bf15
parent47465ab1ccf48d2c905dbcf3b676e30b61cc41ca (diff)
rb_rational_raw: convert num and den by to_int
-rw-r--r--rational.c4
-rw-r--r--test/-ext-/rational/test_rat.rb24
2 files changed, 28 insertions, 0 deletions
diff --git a/rational.c b/rational.c
index 0261c69..1cd4ecc 100644
--- a/rational.c
+++ b/rational.c
@@ -1927,6 +1927,10 @@ rb_gcdlcm(VALUE self, VALUE other)
VALUE
rb_rational_raw(VALUE x, VALUE y)
{
+ if (! RB_INTEGER_TYPE_P(x))
+ x = rb_to_int(x);
+ if (! RB_INTEGER_TYPE_P(y))
+ y = rb_to_int(y);
if (INT_NEGATIVE_P(y)) {
x = rb_int_uminus(x);
y = rb_int_uminus(y);
diff --git a/test/-ext-/rational/test_rat.rb b/test/-ext-/rational/test_rat.rb
index dbba00c..7683483 100644
--- a/test/-ext-/rational/test_rat.rb
+++ b/test/-ext-/rational/test_rat.rb
@@ -42,5 +42,29 @@ class TestRational < Test::Unit::TestCase
rat = Rational.raw(1, -2)
assert_equal(-1, rat.numerator)
assert_equal(2, rat.denominator)
+
+ assert_equal(1/2r, Rational.raw(1.0, 2.0))
+
+ assert_raise(TypeError) { Rational.raw("1", 2) }
+ assert_raise(TypeError) { Rational.raw(1, "2") }
+
+ class << (o = Object.new)
+ def to_i; 42; end
+ end
+
+ assert_raise(TypeError) { Rational.raw(o, 2) }
+ assert_raise(TypeError) { Rational.raw(1, o) }
+
+ class << (o = Object.new)
+ def to_int; 42; end
+ end
+
+ rat = Rational.raw(o, 2)
+ assert_equal(42, rat.numerator)
+ assert_equal(2, rat.denominator)
+
+ rat = Rational.raw(2, o)
+ assert_equal(2, rat.numerator)
+ assert_equal(42, rat.denominator)
end
end