What is happening here??
irb(main):001:0> a= nil
=> nil
irb(main):002:0> b = nil
=> nil
irb(main):003:0> a
=> nil
irb(main):004:0> a+b
NoMethodError: undefined method `+' for nil:NilClass
from (irb):4
from :0
irb(main):005:0> if a.nil? or b.nil?; a,b=0;end;
irb(main):006:0* c = a+b
TypeError: nil can't be coerced into Fixnum
from (irb):6:in `+'
from (irb):6
from :0
irb(main):007:0>
How can you safely perform arithmetic by transforming nil to an number?
Why would you want to add
nil? It’s specifically designed to be something that represents the lack of a value (note:nilis NOT0).If what you’re actually wanting to do is set both values to
0if either is currentlynil, then what you actually want is this:Your mistake in the code above was the
a,b=0portion, which only sets the value ofato0– it setsbtonilbecause the left hand side is looking for two values, and only one is provided on the right (so the others are assumed to benil).