Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoMethodError: undefined method `to_d' for nil:NilClass

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?

like image 737
boar Avatar asked Sep 20 '13 01:09

boar


2 Answers

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.

like image 114
Jim Stewart Avatar answered Oct 18 '22 13:10

Jim Stewart


or (nil.try(:to_d) || 0) + value

like image 42
PGill Avatar answered Oct 18 '22 14:10

PGill