# Re: setting nil to zero

**URL:** <https://www.ruby-forum.com/t/re-setting-nil-to-zero/72276>\
**Category:** Ruby\
**Created:** [February 23, 2006, 11:20am UTC](https://www.ruby-forum.com/t/re-setting-nil-to-zero/72276 "2006-02-23T11:20:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![PeSSSSaS\_Botp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ecd19e/32.png) [@PeSSSSaS\_Botp](https://www.ruby-forum.com/u/PeSSSSaS_Botp)\
**Post date:** [February 23, 2006, 11:20am UTC](https://www.ruby-forum.com/t/re-setting-nil-to-zero/72276/1 "2006-02-23T11:20:34Z")

</div>

Robert K. [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)] :

#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

# 

# 

#

---

<div class="post-metadata">

**Author:** ![PeSSSSaS\_Botp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ecd19e/32.png) [@PeSSSSaS\_Botp](https://www.ruby-forum.com/u/PeSSSSaS_Botp)\
**Post date:** [February 23, 2006, 11:53am UTC](https://www.ruby-forum.com/t/re-setting-nil-to-zero/72276/2 "2006-02-23T11:53:58Z")

</div>

Botp wrote:

> Robert K. [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)] :
> 
> #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

```
