The Ruby Infinite Hash
@tenderlove shows us ruby magic to create an infinite hash:
>> hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) } => {} >> hash['a'] = 1 => 1 >> hash['a'] => 1 >> hash['b'] => {} >> hash['b']['c']['d'] => {}
@tenderlove shows us ruby magic to create an infinite hash:
>> hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) } => {} >> hash['a'] = 1 => 1 >> hash['a'] => 1 >> hash['b'] => {} >> hash['b']['c']['d'] => {}
My name is Brandon Keepers. I like to build things, usually in Ruby or JavaScript. I work at GitHub and live in Holland, MI.
3 Comments
Just like Python’s defaultdict.
> d = defaultdict(dict)> d['a']{}> d['b']['c'] = 1> d['b']['c']1Slick solution, Brandon. Is there a way to make an existing hash “infinite”?
The best I’ve found is this:
h = {:foo => {:bar => 'BAR'}}h.default_proc = Proc.new do |h, k|
h[k] = Hash.new(&h.default_proc)
end
Unfortunately, the default proc doesn’t apply to nested hashes that already exist:
h[:foo][:doesnt_exist] => nilNick: Good question. Cleanest solution would probably be some kind of recursive merge.
Post a Comment