[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Multilevel hash

aartist

5/25/2005 9:47:00 PM

With perl it's easy to write:

$Q{$date}{$song_played} += 1

How I can accomplish the same thing with ruby?

Thanks!

http://pleac.sourceforge.net/pleac_ruby/... didn't help much
here.

3 Answers

gabriele renzi

5/25/2005 9:56:00 PM

0

aartist ha scritto:
> With perl it's easy to write:
>
> $Q{$date}{$song_played} += 1
>
> How I can accomplish the same thing with ruby?
>
> Thanks!
>
> http://pleac.sourceforge.net/pleac_ruby/... didn't help much
> here.
>

>> q={'key'=>{'key2'=>1}}
=> {"key"=>{"key2"=>1}}
>> q['key']['key2']+=1
=> 2
>> q['key']['key2']
=> 2

Joel VanderWerf

5/25/2005 9:59:00 PM

0

aartist wrote:
> With perl it's easy to write:
>
> $Q{$date}{$song_played} += 1
>
> How I can accomplish the same thing with ruby?
>
> Thanks!
>
> http://pleac.sourceforge.net/pleac_ruby/... didn't help much
> here.
>

irb(main):001:0> mh = Hash.new {|h,k| h[k] = {} }
=> {}
irb(main):002:0> mh[1][2] = 3
=> 3
irb(main):003:0> mh
=> {1=>{2=>3}}

You can also do variable-level hashing:

irb(main):006:0> pr = proc {|h,k| h[k] = Hash.new(&pr) }
=> #<Proc:0x4021eb08@(irb):6>
irb(main):007:0> vh = Hash.new(&pr)
=> {}
irb(main):008:0> vh[1][2][3][4] = 5
=> 5
irb(main):009:0> vh
=> {1=>{2=>{3=>{4=>5}}}}

(This is ruby-talk folklore!)


Joel VanderWerf

5/25/2005 10:28:00 PM

0

Joel VanderWerf wrote:
> aartist wrote:
>
>> With perl it's easy to write:
>>
>> $Q{$date}{$song_played} += 1
>>
>> How I can accomplish the same thing with ruby?
>>
>> Thanks!
>>
>> http://pleac.sourceforge.net/pleac_ruby/... didn't help much
>> here.
>>
>
> irb(main):001:0> mh = Hash.new {|h,k| h[k] = {} }
> => {}
> irb(main):002:0> mh[1][2] = 3
> => 3
> irb(main):003:0> mh
> => {1=>{2=>3}}

And if you want automatic zeros:

irb(main):010:0> mh0 = Hash.new {|h,k| h[k] = Hash.new(0)}
=> {}
irb(main):011:0> mh0[1][2] += 1
=> 1
irb(main):012:0> mh0
=> {1=>{2=>1}}