首页 > 解决方案 > Ruby array to hash with dates as keys

问题描述

I have an array that looks like this:

[
  ["20180630", "14:49", "google", "iOS", "Safari", "1"], 
  ["20180630", "12:22", "google", "Android", "Chrome", "2"],
  ["20180629", "17:20", "google", "iOS", "Safari", "1"], 
  ["20180629", "16:30", "(direct)", "iOS", "Safari", "1"], 
  ["20180629", "09:29", "(direct)", "Android", "Chrome", "2"]
]

What I would like to have as an output is a hash where the date serves as the key:

{
  "20180630": [["14:49", "google", "iOS", "Safari", "1"],["12:22", "google", "Android", "Chrome", "2"]],
  "20180629": [[...],[...],[...]]
}

标签: ruby

解决方案


Enumerable#group_by将为您提供数组哈希转换,然后只需从结果值中删除冗余列即可:

hash = input_array.group_by(&:first)
hash.each { |_, list| list.each(&:shift) }
hash

(请注意,这会修改原始数组;如果有问题,您需要调整到具有更多复制和更少突变的版本)


推荐阅读