From: Sebastian Hungerecker Date: 2009-01-05T00:01:09+09:00 Subject: Re: Default values of hashes Glenn wrote: > In other words, if I need 3 levels, it creates a hash within hash object 3 > levels deep (like in the line of code above) and if I need 5, it creates > one 5 levels deep.  I do not know how to do this (or even if it is > possible).  Any suggestions on this one? def nested_hash(levels, def_value=nil, &def_proc) inner_hash = def_proc ? Hash.new(&def_proc) : Hash.new(def_value) if levels == 1 inner_hash else l = [lambda {|h,k| h[k] = inner_hash}] (levels-2).times do |i| l[i+1] = lambda {|h,k| h[k] = Hash.new( &l[i] ) } end Hash.new(&l[-1]) end end This creates a nested hash levels levels deep, where the innermost hash can optionally have a default value or proc. Usage: h = nested_hash(1) # Same as h = Hash.new h = nested_hash(1) {|h,k| h[k] = Array.new} # Same as h = Hash.new {|h,k| h[k] = Array.new} h = nested_hash(3) # Same as h = Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] = Hash.new}} h = nested_hash(3, :foo) # Same as h = Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] = Hash.new(:foo)}} HTH, Sebastian -- Jabber: sepp2k@jabber.org ICQ: 205544826