作者:GuangLi1472_716 | 来源:互联网 | 2023-05-18 18:37
Ineedagroupanarrayofhashesbasedonaparticularkeyofeachhash.Forexample,takethis:我需
I need a group an array of hashes based on a particular key of each hash. For example, take this:
我需要一个基于每个哈希的特定键的哈希数组。例如,拿这个:
[
[0] {
:status => "pending",
:x => 1,
:y => 2
},
[1] {
:status => "pending",
:x => 33,
:y => 74
},
[2] {
:status => "done",
:x => 33,
:y => 74
}
]
I need to convert it to this:
我需要将其转换为:
{
"pending" => [
[0] {
:status => "pending",
:x => 1,
:y => 2
},
[1] {
:status => "pending",
:x => 33,
:y => 74
}
],
"done" => [
[0] {
:status => "done",
:x => 33,
:y => 74
}
]
}
I am grouping the array by :status key. I have done this (it works):
我正在通过以下方式对数组进行分组:status key。我这样做了(它有效):
a.inject({}) {|a, b| (a[b[:status]] ||= []) <
But, is there a simpler, less cryptic one-liner that can do the same thing?
但是,是否有一个更简单,更少神秘的单行程可以做同样的事情?
2 个解决方案
1
It's not a common enough operation to warrant a built-in descriptive method, but I would tweak your line slightly.
保证内置描述性方法并不是一种常见的操作,但我会稍微调整一下你的行。
Instead of using #inject()
, how about using #each_with_object()
? It's more appropriate for passing the same object over an iteration, as that's exactly what it does - it's also more descriptive than "inject", IMO.
而不是使用#inject(),如何使用#each_with_object()?它更适合在迭代中传递相同的对象,因为它正是它所做的 - 它也比“注入”IMO更具描述性。
That has the added benefit of removing the ; a
from the end of the block: this is the problem with using inject to pass the same object between each iteration. Therefore, the final line becomes (with some variable name tweaking):
这有一个额外的好处,即删除;从块的末尾开始:这是使用inject在每次迭代之间传递相同对象的问题。因此,最后一行变为(带有一些变量名称调整):
ary.each_with_object({}) {|e, obj| (obj[e[:status]] ||= []) <
The return value of each_with_object is the hash that's being built up, so you can assign the above to a variable, or return it from your method.
each_with_object的返回值是正在构建的哈希,因此您可以将上述内容分配给变量,或者从方法返回它。
In the end, if you want it to be more descriptive in your application, wrap that line in a method that is descriptive:
最后,如果您希望它在您的应用程序中更具描述性,请将该行包装在描述性方法中:
def index_with_status(ary)
ary.each_with_object({}) {|e, obj| (obj[e[:status]] ||= []) <