Recursively Setting Deep Hash Value

I’ve always wanted to be able to do something like:

my_hash = {}
my_hash["Cloud"]["Stats"]["Strength"] = 100
p my_hash # => {"Cloud"=>{"Stats"=>{"Strength"=>100}}}

So I whipped up the code below and now I can! Metaprogramming wins again!

class SuperHash < Hash
  def initialize
    super { |h, k| h[k] = SuperHash.new }
  end
end

sh = SuperHash.new
sh["foo"]["bar"]["baz"] = "wtf"
pp sh

All this does is set the default value for the SuperHash to a new instance of SuperHash. Very…very cool.

  1. alvira-zimmermann reblogged this from alfuken
  2. alfuken reblogged this from ilovemetaprogramming
  3. ilovemetaprogramming posted this