问题
Suppose I have this array
x=[{:shipping_id=>2, :fsn=>"ab", :price=>300, :quantity=>1},
{:shipping_id=>3, :fsn=>"abc",:price=>500, :quantity=>2},
{:shipping_id=>2, :fsn=>"abcd",:price=>300,:quantity=>3},
{:shipping_id=>4, :fsn=>"abx", :price=>600,:quantity=>1},
{:shipping_id=>3, :fsn=>"abb", :price=>400,:quantity=>1}]
I want to group it by unique shipping id, but in this case let us just group by shipping_id=2
So I do x.select! {|y| y[:shipping_id]==2}
which gives me
[{:shipping_id=>2, :fsn=>"ab",:price=>300,:quantity=>1}, {:shipping_id=>2, :fsn=>"abcd",:price=>300,:quantity=>3}]
But the problem is I want my result in this form
x={:shipping_id=>[2,2],:fsn=>["ab","abcd"],:price=>[300,300],:quantity=>[1,3]}
What should I do? I can do this in a few lines, but is there any optimized way for it?
UPDATE -: Final working solution (My solution)-
Controller
new_params={}
order_hash.each do |row|
new_params=row.convert_to_params(new_params)
end
params.merge!(new_params)
Model
def convert_to_params(new_params)
item=self.instance_values.symbolize_keys
item.each do |k, v|
new_params[k].nil? ? new_params[k]=[v] : new_params[k].push(v)
end
return new_params
end
This gave me my desired result
回答1:
arr = x= [{:shipping_id=>2, :fsn=>"ab"},
{:shipping_id=>3, :fsn=>"abc"}, {:shipping_id=>2, :fsn=>"abcd"},
{:shipping_id=>4, :fsn=>"abx"}, {:shipping_id=>3, :fsn=>"abb"}]
@h = {}
arr.group_by {|x| x[:shipping_id]==2 }[true].inject({}) do |mem,i|
i.each{|k,v| mem[k] = [v] << mem[k] ; @h = mem}
end
p @h #=> {:shipping_id=>[2, 2], :fsn=>["abcd", "ab"]}
回答2:
You could do:
ret = Hash[x.group_by {|e| e[:shipping_id]}.map {|e| [e.first, e.last.map {|t| t[:fsn]}]}]
and then, if you need only the ones for shipping_id = 2
> ret[2]
=> ["ab", "abcd"]
回答3:
Edited:
>> z = x.group_by {|y| y[:shipping_id] }
#=> {2=>[{:shipping_id=>2, :fsn=>"ab"}, {:shipping_id=>2, :fsn=>"abcd"}], 3=>[{:shipping_id=>3, :fsn=>"abc"}, {:shipping_id=>3, :fsn=>"abb"}], 4=>[{:shipping_id=>4, :fsn=>"abx"}]}
>> Hash[z.map {|k, v| Array[[k]*v.count, v] }]
#=> {[2, 2]=>[{:shipping_id=>2, :fsn=>"ab"}, {:shipping_id=>2, :fsn=>"abcd"}], [3, 3]=>[{:shipping_id=>3, :fsn=>"abc"}, {:shipping_id=>3, :fsn=>"abb"}], [4]=>[{:shipping_id=>4, :fsn=>"abx"}]}
Not exactly what you need, still leave it here in case you find it useful somehow.
来源:https://stackoverflow.com/questions/16194778/grouping-via-an-element-in-hash