diff --git a/ext/bigdecimal/lib/bigdecimal/util.rb b/ext/bigdecimal/lib/bigdecimal/util.rb index 0c4e486..58f5ac2 100644 --- a/ext/bigdecimal/lib/bigdecimal/util.rb +++ b/ext/bigdecimal/lib/bigdecimal/util.rb @@ -1,4 +1,26 @@ # frozen_string_literal: false + +# BigDecimal extends the native NilClass class to provide the #to_d method. +# +# When you require BigDecimal in your application, this method will be available +# on nil. +class NilClass + # call-seq: + # nil.to_d -> 0 + # + # Always return 0 in BigDecimal. + # + # require 'bigdecimal' + # require 'bigdecimal/util' + # + # nil.to_d + # # => # + # + def to_d + BigDecimal(0) + end +end + # BigDecimal extends the native Integer class to provide the #to_d method. # # When you require the BigDecimal library in your application, this methodwill diff --git a/test/bigdecimal/test_bigdecimal_util.rb b/test/bigdecimal/test_bigdecimal_util.rb index c3a45b2..d7d60b2 100644 --- a/test/bigdecimal/test_bigdecimal_util.rb +++ b/test/bigdecimal/test_bigdecimal_util.rb @@ -9,6 +9,10 @@ def test_BigDecimal_to_d assert_same(x, x.to_d) end + def test_NilClass_to_d + assert_equal(BigDecimal(0), nil.to_d) + end + def test_Integer_to_d assert_equal(BigDecimal(1), 1.to_d) assert_equal(BigDecimal(2<<100), (2<<100).to_d)