RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

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}}}</pre>
So I whipped up this small code and now I can! Metaprogramming wins again!

Comments

Alternatively, Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) }

@sutto your version does’nt work with ruby 1.8.7 (at least not for me). but 1.9.2 works fine. nice solution, both of you.

Both solutions are nice. But I was wondering if you are familiar with ruby facets. It’s a very cool Ruby library and has a solution for this problem. You can take a look to http://rubyworks.github.com/facets/doc/api/core/Hash.html for the autonew method.

didn’t you already post it, http://www.rubyflow.com/items/5667-recursively-setting-deep-hash-value

christ man, get a life and stop wasting my time

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in