Add exception: keyword in Kernel#Rational()

Support `exception:` keyword argument in `Kernel#Rational()`.
If `exception:` is `false`, `Kernel#Rational()` returns `nil` if the given
value cannot be interpreted as a rational value.
The default value of `exception:` is `true`.
This is part of [Feature #12732].

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62759 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
mrkn 2018-03-15 07:19:46 +00:00
parent 2993b4423d
commit 0dc74b94c2
2 changed files with 161 additions and 64 deletions

View file

@ -805,6 +805,30 @@ class Rational_Test < Test::Unit::TestCase
assert_raise(ZeroDivisionError) {Rational("1/0")}
end
def test_Rational_without_exception
assert_nothing_raised(ArgumentError) {
assert_equal(nil, Rational("5/3x", exception: false))
}
assert_nothing_raised(ZeroDivisionError) {
assert_equal(nil, Rational("1/0", exception: false))
}
assert_nothing_raised(TypeError) {
assert_equal(nil, Rational(Object.new, exception: false))
}
assert_nothing_raised(TypeError) {
assert_equal(nil, Rational(1, Object.new, exception: false))
}
o = Object.new;
def o.to_r; raise; end
assert_nothing_raised(RuntimeError) {
assert_equal(nil, Rational(o, exception: false))
}
assert_nothing_raised(TypeError) {
assert_equal(nil, Rational(1, o, exception: false))
}
end
def test_to_i
assert_equal(1, Rational(3,2).to_i)
assert_equal(1, Integer(Rational(3,2)))