给定一个散列数组,其中每个散列都是{"date":"date_value", "slots":[slots_value]}
,我希望在一个散列数组中收集具有相同日期的散列,并合并slots数组。
输入示例:
[{"date" : "2016/23/12", "slots" : ["a","b"]},
{"date" : "2016/23/12", "slots" : ["c","d","e"]},
{"date" : "2016/24/12", "slots" : ["x"]}
]
示例输出:
[{"date" : "2016/23/12", "slots" : ["a","b","c","d","e"]},
{"date" : "2016/24/12", "slots" : ["x"]}
]
最佳答案
Enumerable#group_by是一个非常强大的散列和数组工具:
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"]}
关于ruby-on-rails - Ruby on Rails-收集具有相同特定值的哈希,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40454527/