From: Bob Hutchison Date: 2007-11-05T12:50:43+09:00 Subject: Re: x=[]; x[:bla][:some_key] does not work? On 3-Nov-07, at 4:44 PM, Sebastian Hungerecker wrote: > > blk = lambda {|h,k| h[k] = Hash.new(&blk)} > x = Hash.new(&blk) > x[:la][:li][:lu][:chunky][:bacon][:foo] = "bar" > > On 4-Nov-07, at 4:34 AM, Jimmy Kofler wrote: > a = Hash.new{|h,k| h[k]=Hash.new(&h.default_proc) } Very nice, Sebastian and Jimmy. Leading to the obvious... class NestedHash < Hash def initialize blk = lambda {|h,k| h[k] = NestedHash.new(&blk)} super(&blk) end end class Hash def Hash.new_nested_hash Hash.new{|h,k| h[k]=Hash.new(&h.default_proc) } end end ... and with no comment on propriety. I've been using Ruby for years and I'm still startled by what you can do when passing blocks to initializers. A few weeks ago I stumbled on this: Hash.new{ | h, k | h[k] = Array.new } which is just a hash of arrays, completely trivial really, but I'd never thought of it before, and now I'm using it all over the place. And I was really impressed with Ruby when I discovered using blocks with gsub. Cheers, Bob ---- Bob Hutchison -- tumblelog at http://www.recursive.ca/so/ Recursive Design Inc. -- weblog at http://www.recursive.ca/hutch http://www.recursive.ca/ -- works on http://www.raconteur.info/cms-for-static-content/home/