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.

On Tue, Dec 10, 2013 at 7:49 AM, selvag selvag [email protected]
wrote:

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.

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, Jess Gabriel y Galn

Selvag R. wrote in post #1130218:

#!/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.

require ‘xkeys’

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

h = {}.extend XKeys::Hash # or ::Auto for arrays on integer keys
h[“company”, “products”] # Note: nil, not {}!

or maybe you prefer:

h[“company”, “products”, :raise => true] # KeyError!

h[“company”, “products”, :else => :not_populated]

h[“company”, “products”] = list

Ruby is very elegant. [] and []= are just method calls with a slightly
different calling syntax, so you can do some very powerful things
(including auto-vivification on write, contextual defaults, etc.).

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