Home > Enterprise >  Converting Ruby array of array into a hash
Converting Ruby array of array into a hash

Time:10-06

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?

CodePudding user response:

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_hash = Hash.new([])

date_array.each do |date|
  formatted_date = Date.parse(date.first).strftime("%Y-%B")
  result_date_hash[formatted_date]  = date
end

Output:

puts result_date_hash 
 => 
{"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", 1127170, "2021-08-27T11:38:42.000 09:00", 1127104],
 "2021-September"=>["2021-09-26T11:38:42.000 09:00", 1127161]} 

CodePudding user response:

use 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") }
  • Related