ruby 将对象数组转换为以字段为键的哈希
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15761306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Array of objects to Hash with a field as the key
提问by Kostas
I have an Array of objects:
我有一个对象数组:
[
#<User id: 1, name: "Kostas">,
#<User id: 2, name: "Moufa">,
...
]
And I want to convert this into an Hash with the idas the keys and the objects as the values. Right now I do it like so but I knowthere is a better way:
我想把它转换成一个 Hashid作为键和对象作为值。现在我这样做,但我知道有更好的方法:
users = User.all.reduce({}) do |hash, user|
hash[user.id] = user
hash
end
The expected output:
预期输出:
{
1 => #<User id: 1, name: "Kostas">,
2 => #<User id: 2, name: "Moufa">,
...
}
回答by tokland
users_by_id = User.all.map { |user| [user.id, user] }.to_h
If you are using Rails, ActiveSupport provides Enumerable#index_by:
如果您使用 Rails,ActiveSupport 提供Enumerable#index_by:
users_by_id = User.all.index_by(&:id)
回答by Sergio Tulentsev
You'll get a slightly better code by using each_with_objectinstead of reduce.
通过使用each_with_object而不是 ,您将获得稍微好一点的代码reduce。
users = User.all.each_with_object({}) do |user, hash|
hash[user.id] = user
end

