From 1193332256d0f6dfacf660a9740e8b28e5ea0c31 Mon Sep 17 00:00:00 2001 From: Piotr Szmielew Date: Sun, 25 Dec 2016 01:11:02 +0100 Subject: [PATCH] fixes issue: #13062 - String#to_d is not raising error This commit fixes issue with String#to_d method which was inconsistent with other to_d methods (String one returned error, while other simply returns 0). Also, there tests added for this case. --- ext/bigdecimal/lib/bigdecimal/util.rb | 6 +++++- test/bigdecimal/test_bigdecimal_util.rb | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/ext/bigdecimal/lib/bigdecimal/util.rb b/ext/bigdecimal/lib/bigdecimal/util.rb index 670a625..8101524 100644 --- a/ext/bigdecimal/lib/bigdecimal/util.rb +++ b/ext/bigdecimal/lib/bigdecimal/util.rb @@ -58,7 +58,11 @@ class String # # => 0.5e0 # def to_d - BigDecimal(self) + begin + BigDecimal(self) + rescue ArgumentError + BigDecimal(0) + end end end diff --git a/test/bigdecimal/test_bigdecimal_util.rb b/test/bigdecimal/test_bigdecimal_util.rb index c3a45b2..3a3772c 100644 --- a/test/bigdecimal/test_bigdecimal_util.rb +++ b/test/bigdecimal/test_bigdecimal_util.rb @@ -48,4 +48,13 @@ def test_Rational_to_d_with_zero_precision def test_Rational_to_d_with_negative_precision assert_raise(ArgumentError) { 355.quo(113).to_d(-42) } end + + def test_String_to_d + assert_equal("2.5".to_d, BigDecimal.new('2.5')) + end + + def test_invalid_String_to_d + assert_equal("invalid".to_d, BigDecimal.new('0.0')) + end + end -- 2.9.3 (Apple Git-75)