rubyruby-hash

Group array of hashes by value and retain structure (hash) in Ruby


I have a hash like this:

  hash = {
    'en-us': {
      where: 'USA'
    },
    'en-us-zone2': {
      where: 'USA'
    },
    'en-nl': {
      where: 'Netherlands'
    },
    'en-pt': {
      where: 'Portugal'
    },
  }

And I tried to group them using group_by:

result = hash.group_by { |k,v| v[:where] }

However, It returns full of array not by array of hashes. So here is expected and actual results:

Actual Result:

{ "USA"=>  
  [[:"en-us", {:where=>"USA"}], [:"en-us-zone2", {:where=>"USA"}]], 
 "Netherlands"=>
  [[:"en-nl", {:where=>"Netherlands"}]],
 "Portugal"=>
  [[:"en-pt", {:where=>"Portugal"}]]
}

Expected Result:

{ "USA"=>
   [{:"en-us" => {:where=>"USA"}}, {:"en-us-zone2" => {:where=>"USA"}}]
  "Netherlands"=>
   [{:"en-nl" => {:where=>"Netherlands"}}]
  "Portugal"=>
   [{:"en-pt" => {:where=>"Portugal"}}]
}

See, Actual is Array of arrays, instead of array of hashes. Hash keys becomes first array element.

How can I group my hash based on :where ?


Solution

  • This should work:

    hash.group_by { |k,v| v[:where] }.each { |_, v| v.map! { |array| { array[0] => array[1] } } }
    

    Or with transform_values

    hash.group_by { |k,v| v[:where] }.transform_values { |v| v.map { |array| {array[0] => array[1] } } }
    

    https://ruby-doc.org/core-2.4.0/Hash.html#method-i-transform_values