multiple level hash assignment equivalence to perl

D

don mc

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
 
J

Joel VanderWerf

don said:
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}}}}
 
D

don mc

Thanks! Thats just what I needed.

Regards,
Don

Joel said:
don said:
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}}}}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top