NoMethodError: undefined method `to_d' for nil:NilClass
this seems to be inconsistent with other "to_"
eg with Rails 3.2.14, and ruby 1.9.3p362:
1.9.3p362 :055 > nil.to_f
=> 0.0
1.9.3p362 :056 > nil.to_d
NoMethodError: undefined method `to_d' for nil:NilClass
1.9.3p362 :057 > nil.to_s
=> ""
1.9.3p362 :058 > nil.to_i
=> 0
it means that when ever i might want to convert to big decimal that i first have to make sure the value is not nil and assign it a 0 value anyway... so... comments on what is the best way to make this consistent? and should i consider this a bug?
to_d
isn't part of core Ruby. It's part of the BigDecimal package; specifically you get it when you require "bigdecimal/util"
. It monkey-patches itself into some of the core classes, but as you've discovered, not all of them.
If you just want nil.to_d
to return nil
(which seems like the only sensible thing for it to return), you can monkey-patch it yourself:
class NilClass
def to_d
nil
end
end
irb(main):015:0> nil.to_d
=> nil
If you want it to return an actual BigDecimal with value 0, then return BigDecimal.new(0)
instead, but I think nil
should be nil
.
or
(nil.try(:to_d) || 0) + value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With