[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Hash of arrays - strange behavior.

Jakub Kuzma

10/3/2007 10:03:00 AM

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.

--
Jakub Kuzma
http...
JID oraz e-mail w domenie gmail.com, login - qoobaa
2 Answers

Sebastian Hungerecker

10/3/2007 10:16:00 AM

0

Jakub Kuzma 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
--
Jabber: sepp2k@jabber.org
ICQ: 205544826

Jakub Kuzma

10/3/2007 10:20:00 AM

0

Dnia Wed, 3 Oct 2007 19:15:35 +0900
Sebastian Hungerecker <sepp2k@googlemail.com> 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 :-).

> Sebastian

--
Jakub Kuzma
http...
JID oraz e-mail w domenie gmail.com, login - qoobaa