Transform 2 d hash into 1 d hash
With this Hash:
{ "blog_namespace" : { "key" : "blog_post_1234",
"notice" : "Read the new blog post!开发者_C百科" } }
What's the quickest way to translate it into the Hash:
{ "blog_post_1234" : "Read the new blog post!" }
?
I always see people using clever combinations of map
and merge
etc, but can't quite get my head around a way to do this without nesting two loops together.
These hashes appear to be JSON objects. If they are, use a JSON parser to transform them into ruby hashes.
hash = {"blog_namespace" => {"key" => "blog_post_1234",
"notice" => "Read the new blog post!"}}
Hash[hash.map {|k, v| [v["key"], v["notice"]] }]
# => {"blog_post_1234" => "Read the new blog post!"}
This wasn't a valid Ruby hash. But given the assumptions that it is (or you'll parse it into one) and that the key will always be "blog_namespace"
, you can do the following:
>> Hash[[h["blog_namespace"].values]]
#=> {"blog_post_1234"=>"Read the new blog post!"}
精彩评论