Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, what is the best way to compact a hash into a nested hash

Say I have this:

[
  { :user_id => 1, :search_id => a},
  { :user_id => 1, :search_id => b},
  { :user_id => 2, :search_id => c},
  { :user_id => 2, :search_id => d}
]

and I want to end up with:

[
  { :user_id => 1, :search_id => [a,b]},
  { :user_id => 2, :search_id => [c,d]}
]

What is the best way to do that?

like image 874
kidbrax Avatar asked Dec 06 '11 17:12

kidbrax


People also ask

What is nested hash?

Nested hashes allow us to further group, or associate, the data we are working with. They help us to deal with situations in which a category or piece of data is associated not just to one discrete value, but to a collection of values.

Are nested hashes possible in Ruby?

The hashes that you've seen so far have single key/value pairs. However, just like arrays, they can be nested, or multidimensional.

How do you add a hash to an array in Ruby?

You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.


1 Answers

Very strange requirement indeed. Anyway

[ { :user_id => 1, :search_id => "a"},
  { :user_id => 1, :search_id => "b"},
  { :user_id => 2, :search_id => "c"},
  { :user_id => 2, :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) } }
like image 177
Victor Moroz Avatar answered Sep 17 '22 23:09

Victor Moroz