在 Ruby 中重新映射哈希的最佳方法是什么?
是否有一种简单的方法可以通过以下方式重新映射 ruby 中的哈希值:
from:
{:name => "foo", :value => "bar"}
to:
{"foo" => "bar"}
最好是在迭代此类哈希值的数组时使执行此操作变得简单的方式:
from:
[{:name => "foo", :value => "bar"}, {:name => "foo2", :value => "bar2"}]
to:
{"foo" => "bar", "foo2" => "bar2"}
谢谢。
Is there a simple way of remapping a hash in ruby the following way:
from:
{:name => "foo", :value => "bar"}
to:
{"foo" => "bar"}
Preferably in a way that makes it simple to do this operation while iterating over an array of this type of hashes:
from:
[{:name => "foo", :value => "bar"}, {:name => "foo2", :value => "bar2"}]
to:
{"foo" => "bar", "foo2" => "bar2"}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Vanson Samuel 代码的修改版本达到了预期目的。
这是一篇单行诗,但相当长。
不过,我不会说它比 Gishu 的版本更漂亮。
A modified version of Vanson Samuel's code does the intended.
It's a one-liner, but quite a long one.
I wouldn't say that it's prettier than Gishu's version, though.
作为一般经验法则,如果您有 {:name => 形式的哈希值 “foo”,:值=> "bar"},通常最好使用 ["foo", "bar"] 元组。
As a general rule of thumb, if you have a hash of the form {:name => "foo", :value => "bar"}, you're usually better off with using a tuple of ["foo", "bar"].
我知道这很旧,但实现此目的的最巧妙方法是将哈希数组映射到元组数组,然后使用 Hash[] 从中构建哈希,如下所示:
I know this is old, but the neatest way to achieve this is to map the array of hashes to an array of tuples, then use Hash[] to build a hash from that, as follows:
有点晚了但是:
a bit late but: