Multiple level hash assignment equivalence to perl

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

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:[email protected]:2(irb)
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}}}}

On Thu, 13 Jul 2006, Joel VanderWerf wrote:

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:[email protected]:2(irb)
irb(main):003:0> h = Hash.new(&pr)
^^
^^

nice! my approach is slightly more verbose.

-a

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:[email protected]:2(irb)
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}}}}

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs