# Re: setting nil to zero

#1

#f[w] = (f[w] || 0) + 1

clear rubyish solution, Robert.
thanks again for generous help.

i am still hoping for the plain f[w] += 1 though

for the record, i played w the ff

ruby>cat test.rb

class NilClass
def method_missing(methId, *args)
str = methId.id2name
if str == â€ś+â€ť and args[1].nil?
#str is â€ś+â€ť
#args[1] is nil
#args[0] is rhs value
return args[0]
end
end
end

f = {}
f[â€śtestâ€ť] += 1
f[â€śtest2â€ť] += 2
p f

f = []
f[1] += 1
f[5] += 2
p f

ruby>ruby test.rb
{â€śtest2â€ť=>2, â€śtestâ€ť=>1}
[nil, 1, nil, nil, nil, 2]

ruby>

I doubted if itâ€™s robust enough, so my qâ€¦

-botp

#Kind regards

# robert

#2

Botp wrote:

#f[w] = (f[w] || 0) + 1

clear rubyish solution, Robert.
thanks again for generous help.

i am still hoping for the plain f[w] += 1 though

As mentioned already you can do that, if itâ€™s a Hash:

f=Hash.new 0
=> {}

f[:foo]+=1
=> 1

f
=> {:foo=>1}

``````     #args[0]  is rhs value
return args[0]
end
``````

end
end

Why so complicated? Why not just

class NilClass
def +(n) n end
end

h={}
=> {}

h[:foo]+=1
=> 1

h
=> {:foo=>1}

Note, I recommend to use the veriant with 0 as default value for Hash
lookups because that avoids tampering with standard classes.

Cheers

``robert``