blk = lambda {|h,k| h[k] = Hash.new(&blk)}
x = Hash.new(&blk)
x[:la][:li][:lu][:chunky][:bacon][:foo] = "bar"
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