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.
-
alvira-zimmermann reblogged this from alfuken
-
invisible-detector liked this
-
website-value liked this
-
fonsan liked this
-
gluecode liked this
-
alfuken reblogged this from ilovemetaprogramming
