RubyFlow The Ruby and Rails community linklog

Recursively Setting Deep Hash Value

Ever want to set a Hash like below? Check out my short blog post.

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

Comments

I like meta-progamming as well but this post is lame. First this topic has been discussed previously on Ruby Forum. Next I fail to see what is so meta about the solution. You are just defining a new class and using recursion. Next all of this can be achieved in one line (I am not the original author of the following):

ruby-1.9.2-p180 > sh = Hash.new{|h,k| h[k]=Hash.new(&h.default_proc)} => {} ruby-1.9.2-p180 > sh[:a][:b][‘c’][1] = ‘wtf’ => “wtf” ruby-1.9.2-p180 > sh => {:a=>{:b=>{“c”=>{1=>”wtf”}}}}

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