# Hash

**URL:** <https://rubytalk.org/t/hash/75943>\
**Category:** ruby-talk\
**Created:** [4 June 2022 05:11 UTC](https://rubytalk.org/t/hash/75943 "2022-06-04T05:11:19Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![Xavier\_Noria](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/xavier_noria/32/1867_2.png) [@Xavier\_Noria](https://rubytalk.org/u/Xavier_Noria)\
**Post date:** [4 June 2022 05:42 UTC](https://rubytalk.org/t/hash/75943/3 "2022-06-04T05:42:49Z")

</div>

It is the same as:

irb(main):001:0\> h = Hash.new(0)  
=\> {}  
irb(main):002:0\> h[1]  
=\> 0  
irb(main):003:0\> h  
=\> {}

A default value is just returned if the key does not exist in the hash, not  
assigned.

Your example takes the returned value and mutates it, that may mud the  
waters, but perhaps the 0 example above clarifies.

Even worse. The \*same\* array reference is returned for every key miss. The  
default value is one particular object, the one you passed to Hash.new.  
Therefore, this happens:

irb(main):001:0\> h = Hash.new()  
=\> {}  
irb(main):002:0\> h[1] \<\< 1  
=\> [1]  
irb(main):003:0\> h[2] \<\< 1  
=\> [1, 1]  
irb(main):004:0\> h[3] \<\< 1  
=\> [1, 1, 1]

See, same array reference mutated multiple times (and no entry effectively  
created in the hash, still).

The idiomatic way to do this like you expect is John's solution.

---

_[View the full topic](https://rubytalk.org/t/hash/75943)._
