说我有这个:
[ { :user_id => 1,:search_id => a},{ :user_id => 1,:search_id => b},{ :user_id => 2,:search_id => c},:search_id => d} ]
我想最终得到:
[ { :user_id => 1,:search_id => [a,b]},:search_id => [c,d]} ]
最好的方法是什么?
解决方法
确实非常奇怪的要求.无论如何
[ { :user_id => 1,:search_id => "a"},:search_id => "b"},:search_id => "c"},:search_id => "d"} ] \ .map{ |h| h.values_at(:user_id,:search_id) } \ .group_by(&:first) \ .map{ |k,v| { :user_id => k,:search_id => v.map(&:last) } }