back to notes

Mimic Array.to_h in Ruby 2.0

# Order the hash by number of ids in reverse order 

country_2_ids = {
  'FRA' => [1 , 2, 3], 
  'USA' => [4, 5, 6, 7], 
  'UK' => [8, 9 ]
}

country_2_ids
  .sort_by { |country, ids| ids.size}
    .tap { |country, ids| p country, ids} 
      # ["UK", [8, 9]]
      # ["FRA", [1, 2, 3]]
      # ["USA", [4, 5, 6, 7]]
  .reverse
    .tap { |country, ids| p country, ids} 
      # ["USA", [4, 5, 6, 7]]
      # ["FRA", [1, 2, 3]]
      # ["UK", [8, 9]]
  .map { |country, ids| { country => ids}}
    .tap { |country, ids| p country, ids} 
      # [ { "USA" => [4, 5, 6, 7] } ]
      # [ { "FRA" => [1, 2, 3]      } ]
      # [ { "UK"  => [8, 9]         } ]
  .reduce(:merge)

# {
#   "USA"=>[4, 5, 6, 7], 
#   "FRA"=>[1, 2, 3], 
#   "UK"=>[8, 9]
# }


last updated september 2015