我有以下
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 中有什么优雅的方法吗?
Hash[friends.map { |f| _f = f.dup; [_f.delete(:name), _f] }]
# => {"Jack"=>{:attr1=>"def", :attr2=>"def"}, "Jill"=>{:attr1=>"def", :attr2=>"def"}}
friends.each_with_object({}) do |f, o|
f = f.dup
o[f.delete :name] = f
end
hash = {}
friends.each{|h| hash[h.delete(:name)] = h }
# => {"Jack"=>{:attr1=>"def", :attr2=>"def"}, "Jill"=>{:attr1=>"def", :attr2=>"def"}}
当您想将一个数组转换为另一个数组时,请使用collect
:
friends = Hash[
friends.collect do |f|
_f = f.dup
name = _f.delete(:name)
[ name, _f ]
end
]
您可以轻松地创建一个新的散列Hash[]
,并为其提供一个包含一系列键/值对的数组。在这种情况下,该name
字段将从每个中删除。
如果我们将“优雅”理解为通过利用可重用抽象来编写简洁代码的方式,我会写:
require 'active_support/core_ext/hash'
require 'facets/hash'
friends.mash { |f| [f[:name], f.except(:name)] }
无需为这两个相当大的库添加 gem 依赖项,您始终可以在扩展库中实现各个方法。