0

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 ?

mechnicov
  • 12,025
  • 4
  • 33
  • 56
Dennis
  • 1,805
  • 3
  • 22
  • 41

2 Answers2

1

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

1

It's ugly but works:

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

hash.
  group_by { |_, v| v[:where] }.
  map do |k, v|
    [
      k,
      v.map { |a, b| {a => b} }
    ]
  end.to_h

# => {"USA"=>[{:"en-us"=>{:where=>"USA"}}, {:"en-us-zone2"=>{:where=>"USA"}}], "Netherlands"=>[{:"en-nl"=>{:where=>"Netherlands"}}], "Portugal"=>[{:"en-pt"=>{:where=>"Portugal"}}]}
mechnicov
  • 12,025
  • 4
  • 33
  • 56