Forcing a zero to a number

What's going on 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 do arithmetic by converting nil to a number?

+3
source share
3 answers

Why do you want to add nil? It is specifically designed to be something that represents a lack of meaning (note: nilNOT 0).

If what you really want to do is set both values ​​to 0, if at the moment it is nil, then you really want to:

if a.nil? or b.nil?; a,b=0,0; end

a,b=0, a 0 - b nil, , ( nil).

+3

, , , nil 0; - :

c = (a || 0) + (b || 0)

, , , , ...

+5

(a, b = 0) a=0 b=nil, 0 a nil - b, .

:    a.nil? b.nil?; a = b = 0;   c = a + b

Obviously, the code is still broken, since you are overwriting any values ​​other than aand b, with 0, when aor bis zero.

+3
source

Source: https://habr.com/ru/post/1734217/


All Articles