Omar Lahlou Omar Lahlou - 26 days ago 12
Ruby Question

Ruby on Rails - Gather hashes with same specific value

Given a an array of hashes where every hash is like

{"date":"date_value", "slots":[slots_value]}
, I'd like to gather hashes with the same dates on one hash and merge slots arrays.

Example input:

[{"date" : "2016/23/12", "slots" : ["a","b"]},
{"date" : "2016/23/12", "slots" : ["c","d","e"]},
{"date" : "2016/24/12", "slots" : ["x"]}
]


Example output:

[{"date" : "2016/23/12", "slots" : ["a","b","c","d","e"]},
{"date" : "2016/24/12", "slots" : ["x"]}
]

Answer

Enumerable#group_by is a very powerful tool for Hashes and Arrays :

input = [
  {"date" => "2016/23/12" ,  "slots" => ["a","b"]},
  {"date" => "2016/23/12", "slots" => ["c","d","e"]},
  {"date" => "2016/24/12", "slots" => ["x"]}
]

puts input.group_by{|h| h["date"]}.map{|date, hashes|
  {
    "date" => date,
    "slots" => hashes.map{|h| h["slots"]}.flatten
  }
}
#=> {"date"=>"2016/23/12", "slots"=>["a", "b", "c", "d", "e"]}
#   {"date"=>"2016/24/12", "slots"=>["x"]}
Comments