From: "David A. Black" Date: 2009-01-05T06:22:37+09:00 Subject: Re: Default values of hashes --1926193751-1145626489-1231104219=:19706 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1145626489-1231104219=:19706" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1145626489-1231104219=:19706 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Mon, 5 Jan 2009, Sebastian Hungerecker wrote: > 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. =A0I do not know how to do this (or even if it is >> possible). =A0Any suggestions on this one? > > def nested_hash(levels, def_value=3Dnil, &def_proc) > inner_hash =3D def_proc ? Hash.new(&def_proc) : Hash.new(def_value) > if levels =3D=3D 1 > inner_hash > else > l =3D [lambda {|h,k| h[k] =3D inner_hash}] > (levels-2).times do |i| > l[i+1] =3D lambda {|h,k| h[k] =3D Hash.new( &l[i] ) } > end > Hash.new(&l[-1]) > end > end > > This creates a nested hash levels levels deep, where the innermost hash c= an > optionally have a default value or proc. > > Usage: > h =3D nested_hash(1) > # Same as h =3D Hash.new > > h =3D nested_hash(1) {|h,k| h[k] =3D Array.new} > # Same as h =3D Hash.new {|h,k| h[k] =3D Array.new} > > h =3D nested_hash(3) > # Same as h =3D Hash.new {|h,k| h[k] =3D Hash.new {|h,k| h[k] =3D Hash.ne= w}} > > h =3D nested_hash(3, :foo) > # Same as h =3D Hash.new {|h,k| h[k] =3D Hash.new {|h,k| h[k] =3D Hash.ne= w(:foo)}} Why not make it just keep going automatically? (See my other post.) David --=20 David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com =3D> Independent, social wishlist management! --1926193751-1145626489-1231104219=:19706-- --1926193751-1145626489-1231104219=:19706--