Grouping an array based on its first element without duplication in Ruby
I am running the active write command Product.pluck (: category_id ,: price) which returns an array of 2 arrays of items:
[
[1, 500],
[1, 100],
[2, 300]
]
I want to group by the first element by creating a hash that looks like this:
{1 => [500, 100], 2 => [300]}
group_by seems logical, but replicates the entire array. That is, a.group_by (&: first) produces:
{1=>[[1, 500], [1, 100]], 2=>[[2, 300]]}
+3
source to share
3 answers