# Hash of arrays - strange behavior

**URL:** <https://www.ruby-forum.com/t/hash-of-arrays-strange-behavior/116198>\
**Category:** Ruby\
**Created:** [October 3, 2007, 12:05pm UTC](https://www.ruby-forum.com/t/hash-of-arrays-strange-behavior/116198 "2007-10-03T12:05:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jakub\_KuSSSSma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/54ee81/32.png) [@Jakub\_KuSSSSma](https://www.ruby-forum.com/u/Jakub_KuSSSSma)\
**Post date:** [October 3, 2007, 12:05pm UTC](https://www.ruby-forum.com/t/hash-of-arrays-strange-behavior/116198/1 "2007-10-03T12:05:56Z")

</div>

Hello,

Could somebody explain me the following behavior?

irb(main):001:0\> h = Hash.new([])  
=\> {}  
irb(main):002:0\> h[1].push(1)  
=\> [1]  
irb(main):003:0\> h  
=\> {}  
irb(main):004:0\> h[1].push(1)  
=\> [1, 1]  
irb(main):005:0\> h  
=\> {}  
irb(main):006:0\> h[1].push(1)  
=\> [1, 1, 1]  
irb(main):007:0\> h[1]  
=\> [1, 1, 1]

I can’t get values using ‘each’ method for example.

TIA.

---

<div class="post-metadata">

**Author:** ![Jakub\_KuSSSSma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/54ee81/32.png) [@Jakub\_KuSSSSma](https://www.ruby-forum.com/u/Jakub_KuSSSSma)\
**Post date:** [October 3, 2007, 12:16pm UTC](https://www.ruby-forum.com/t/hash-of-arrays-strange-behavior/116198/2 "2007-10-03T12:16:28Z")

</div>

Jakub KuÅºma wrote:

> Hello,
> 
> Could somebody explain me the following behavior?
> 
> irb(main):001:0\> h = Hash.new([])  
> =\> {}  
> irb(main):002:0\> h[1].push(1)  
> =\> [1]  
> irb(main):003:0\> h  
> =\> {}

Hash.new(arg) makes arg the default, but it doesn’t assign to the hash.  
You  
want h = Hash.new {|h,k| h[k] = []}

HTH,  
Sebastian

---

<div class="post-metadata">

**Author:** ![Jakub\_KuSSSSma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/54ee81/32.png) [@Jakub\_KuSSSSma](https://www.ruby-forum.com/u/Jakub_KuSSSSma)\
**Post date:** [October 3, 2007, 12:21pm UTC](https://www.ruby-forum.com/t/hash-of-arrays-strange-behavior/116198/3 "2007-10-03T12:21:09Z")

</div>

Dnia Wed, 3 Oct 2007 19:15:35 +0900  
Sebastian H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Hash.new(arg) makes arg the default, but it doesn’t assign to the  
> hash. You want h = Hash.new {|h,k| h[k] = []}
> 
> HTH,

Thank you very much :-).
