ruby - 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": [[...],[...],[...]]
}
解决方案
Enumerable#group_by
将为您提供数组哈希转换,然后只需从结果值中删除冗余列即可:
hash = input_array.group_by(&:first)
hash.each { |_, list| list.each(&:shift) }
hash
(请注意,这会修改原始数组;如果有问题,您需要调整到具有更多复制和更少突变的版本)
推荐阅读
- reactjs - 自定义钩子能否确定调用它的组件?
- angular - 如何使用角度从html中的数组中提取前两个字符?
- python - 如何每 x 秒重复调用 API 来更新坐标?
- javascript - 文件夹结构中的JS导入
- mysql - 如何在没有唯一值的两个表之间设置外键?
- reactjs - 仅当未使用 @azure/msal-react 进行身份验证时才重定向 onLoad
- javascript - 除非我刷新页面,否则 Vue data() 对象输入 v-model 不起作用
- postgresql - checkpoint_completion_target 被忽略
- python - 将两个不相等的列表压缩到字典中。如果 key 没有值,则不给出。忽略没有键的值
- vb.net - SQL Server 通配符 LIKE 搜索