Nested_Hash_Creation_in_Ruby

#!/usr/bin/ruby
#hash_of_hash.rb

list={"app1"=>101,"app2"=>104,"app3"=>109,"app4"=>123}

h=Hash.new{ |h,id| h[id]=Hash.new{ |h,dt| h[dt]={} }}
h["company"]["products"]=list
puts h

# edit this code if you've much easier format than this one.
# output should be same.

···

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

Arbitrary nesting:

1.9.3-p448 :001 > h = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
=> {}
1.9.3-p448 :002 > h[1][2][3][4] = true
=> true
1.9.3-p448 :003 > h
=> {1=>{2=>{3=>{4=>true}}}}

Jesus.

···

On Tue, Dec 10, 2013 at 7:49 AM, selvag selvag <lists@ruby-forum.com> wrote:

#!/usr/bin/ruby
#hash_of_hash.rb

list={"app1"=>101,"app2"=>104,"app3"=>109,"app4"=>123}

h=Hash.new{ |h,id| h[id]=Hash.new{ |h,dt| h[dt]={} }}
h["company"]["products"]=list
puts h

# edit this code if you've much easier format than this one.
# output should be same.

Great!

h = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}

To understand, I've had to put a (unecessary) parenthesis.

h = Hash.new {|h,k| h[k] = Hash.new(&(h.default_proc))}

They are the same, aren't they?

It passes the default_proc of h as a block (&) creating the recursion.

I haven't seen this form before!

Congratulations.

Abinoam Jr.

···

On Tue, Dec 10, 2013 at 7:07 AM, Jesús Gabriel y Galán <jgabrielygalan@gmail.com> wrote:

On Tue, Dec 10, 2013 at 7:49 AM, selvag selvag <lists@ruby-forum.com> wrote:

#!/usr/bin/ruby
#hash_of_hash.rb

list={"app1"=>101,"app2"=>104,"app3"=>109,"app4"=>123}

h=Hash.new{ |h,id| h[id]=Hash.new{ |h,dt| h[dt]={} }}
h["company"]["products"]=list
puts h

# edit this code if you've much easier format than this one.
# output should be same.

Arbitrary nesting:

1.9.3-p448 :001 > h = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
=> {}
1.9.3-p448 :002 > h[1][2][3][4] = true
=> true
1.9.3-p448 :003 > h
=> {1=>{2=>{3=>{4=>true}}}}

Jesus.