arrays - Converting Ruby array of array into a hash
问题描述
I have an array of arrays as below :
[
["2021-07-26T11:38:42.000+09:00", 1127167],
["2021-08-26T11:38:42.000+09:00", 1127170],
["2021-09-26T11:38:42.000+09:00", 1127161],
["2021-07-25T11:38:42.000+09:00", 1127177],
["2021-08-27T11:38:42.000+09:00", 1127104]
]
What i want to have as the output :
{
"2021-July" => [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-07-25T11:38:42.000+09:00", 1127177]],
"2021-August" => [["2021-08-26T11:38:42.000+09:00", 112717],["2021-08-27T11:38:42.000+09:00", 112710]],
"2021-September" => ["2021-09-26T11:38:42.000+09:00", 112716]
}
I want to create the hash key year-month
format based on the date value in each array element. What would be the easiest way to do this?
解决方案
利用group_by
date_array = [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-08-26T11:38:42.000+09:00", 112717],["2021-09-26T11:38:42.000+09:00", 112716],["2021-07-25T11:38:42.000+09:00", 1127177],["2021-08-27T11:38:42.000+09:00", 112710]]
result = date_array.group_by{ |e| Date.parse(e.first).strftime("%Y-%B") }
推荐阅读
- excel - 动态合并和堆叠多组列 - Power Query
- javascript - twilio 让本地参与者离开房间
- javascript - 在哪里修改 plyr 源代码中 data-plyr-embed-id 的值?
- powershell - 调用doxygen时在Powershell中配置一些变量
- azure - 启动程序集 Microsoft.ApplicationInsights.StartupBootstrapper 无法执行。有关更多详细信息,请参阅内部异常
- javascript - 如何验证文本框的第一个字符是 Alpha 和 JavaScript 中的第二个字符数字?
- ruby-on-rails - Rails FactoryBot 未初始化常量 Mentor
- javascript - Javascript在最大数量内分隔字符串
- python - 有什么方法可以使用变量而不是文字来更改带有 .format() 的浮点数的小数位数?
- java - 调用将字符串数组作为参数的方法导致 IllegalArgumentException