1

我有以下

friends = [{ name: "Jack", attr1:"def", attr2:"def" }, { name: "Jill", attr1:"def", attr2:"def" }]

我想将上面的表示转换成这样的哈希值

friends = { "Jack" => { attr1: "def", attr2:"def" }, "Jill" => { attr1: "def", attr2: "def" } }

在 Ruby 中有什么优雅的方法吗?

4

5 回答 5

6
Hash[friends.map { |f| _f = f.dup; [_f.delete(:name), _f] }]
# => {"Jack"=>{:attr1=>"def", :attr2=>"def"}, "Jill"=>{:attr1=>"def", :attr2=>"def"}}
于 2012-06-27T15:42:16.990 回答
3
friends.each_with_object({}) do |f, o|
    f = f.dup
    o[f.delete :name] = f
end
于 2012-06-27T15:44:08.650 回答
2
hash = {}
friends.each{|h| hash[h.delete(:name)] = h }
# => {"Jack"=>{:attr1=>"def", :attr2=>"def"}, "Jill"=>{:attr1=>"def", :attr2=>"def"}}
于 2012-06-27T15:45:53.023 回答
1

当您想将一个数组转换为另一个数组时,请使用collect

friends = Hash[
  friends.collect do |f|
    _f = f.dup
    name = _f.delete(:name)
    [ name, _f ]
  end
]

您可以轻松地创建一个新的散列Hash[],并为其提供一个包含一系列键/值对的数组。在这种情况下,该name字段将从每个中删除。

于 2012-06-27T15:43:50.050 回答
1

如果我们将“优雅”理解为通过利用可重用抽象来编写简洁代码的方式,我会写:

require 'active_support/core_ext/hash'
require 'facets/hash'
friends.mash { |f| [f[:name], f.except(:name)] }

无需为这两个相当大的库添加 gem 依赖项,您始终可以在扩展库中实现各个方法。

于 2012-06-27T16:26:28.917 回答