From: Glenn Date: 2009-01-05T10:47:16+09:00 Subject: Re: Default values of hashes --0-1927072347-1231120097=:79439 Content-Type: text/plain; charset=us-ascii Hi David, In your other post, there is no default value for the innermost hash. hproc = lambda {|h,k| h[k] = Hash.new(&hproc) } hash = Hash.new(&hproc) So if I try to increment on a key that isn't there yet, like this: hash[1][2][3] += 1 I get an undefined method for hash error. Am I using it correctly if I want the inner hash to have a default? Please forgive me if I have missed something in your example. I am still relatively new to Ruby and am trying to get to the next level by writing more sophisticated programs. Thanks, Glenn ________________________________ From: David A. Black To: ruby-talk ML Sent: Sunday, January 4, 2009 4:22:37 PM Subject: Re: Default values of hashes 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. 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)}} Why not make it just keep going automatically? (See my other post.) David -- 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 => Independent, social wishlist management! --0-1927072347-1231120097=:79439--