首页 > 解决方案 > 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?

标签: arraysruby-on-railshash

解决方案


利用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") }

推荐阅读