[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

multiple level hash assignment equivalence to perl

don mc

7/12/2006 8:42:00 PM

Is there a succinct way in ruby to do a multiple level hash assignement?
I am more
used to perl, which you can do something like


$hp->{level1}->{level2} = 3

even if the first and second level had never existed below.

Any help would be appreciated.

Regards,
Don Mc

--
Posted via http://www.ruby-....

3 Answers

Joel VanderWerf

7/12/2006 8:52:00 PM

0

don mc wrote:
> Is there a succinct way in ruby to do a multiple level hash assignement?
> I am more
> used to perl, which you can do something like
>
>
> $hp->{level1}->{level2} = 3
>
> even if the first and second level had never existed below.

There's an autovivification trick, using the default proc of a hash (see
ri default_proc):

irb(main):002:0> pr = proc {|h,k| h[k]=Hash.new(&pr) }
=> #<Proc:0x02c15618@(irb):2>
irb(main):003:0> h = Hash.new(&pr)
=> {}
irb(main):004:0> h[1][2][3][4] = 5
=> 5
irb(main):005:0> h
=> {1=>{2=>{3=>{4=>5}}}}

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

don mc

7/12/2006 8:59:00 PM

0

Thanks! Thats just what I needed.

Regards,
Don

Joel VanderWerf wrote:
> don mc wrote:
>> Is there a succinct way in ruby to do a multiple level hash assignement?
>> I am more
>> used to perl, which you can do something like
>>
>>
>> $hp->{level1}->{level2} = 3
>>
>> even if the first and second level had never existed below.
>
> There's an autovivification trick, using the default proc of a hash (see
> ri default_proc):
>
> irb(main):002:0> pr = proc {|h,k| h[k]=Hash.new(&pr) }
> => #<Proc:0x02c15618@(irb):2>
> irb(main):003:0> h = Hash.new(&pr)
> => {}
> irb(main):004:0> h[1][2][3][4] = 5
> => 5
> irb(main):005:0> h
> => {1=>{2=>{3=>{4=>5}}}}


--
Posted via http://www.ruby-....

Ara.T.Howard

7/12/2006 9:28:00 PM

0