Creating Nested Hash in Ruby

Single line code!

block = lambda {|hash, key| hash[key] = Hash.new(&block)}

nested_hash = Hash.new(&block)

nested_hash[:one] = “1”
nested_hash[:two][:sub1] = “2.1”
nested_hash[:two][:sub2] = “2.2”
nested_hash[:three][:sub1][:subsub1] = “3.1.1”
nested_hash[:three][:sub1][:subsub2] = “3.1.2”
nested_hash[:three][:sub2] = “3.2”

Result Hash:

{:one=>”1″, :two=>{:sub1=>”2.1″, :sub2=>”2.2″}, :three=>{:sub1=>{:subsub1=>”3.1.1″, :subsub2=>”3.1.2″}, :sub2=>”3.2″}}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s