将2 d哈希转换为1 d哈希

d11*_*wtq 2 ruby hash map

有了这个哈希:

{ "blog_namespace" : { "key" : "blog_post_1234",
                       "notice" : "Read the new blog post!" } }
Run Code Online (Sandbox Code Playgroud)

将它转换为Hash的最快方法是什么:

{ "blog_post_1234" : "Read the new blog post!" }
Run Code Online (Sandbox Code Playgroud)

我总是看到人们使用的巧妙组合mapmerge等,但不能完全得到我的头周围的方式来做到这一点没有嵌套两个循环在一起.

Gui*_*nal 8

这些哈希值似乎是JSON对象.如果是,请使用JSON解析器将它们转换为ruby哈希值.

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!"}
Run Code Online (Sandbox Code Playgroud)