1

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?

2 Answers 2

2

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") }
Sign up to request clarification or add additional context in comments.

Comments

1
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]} 

2 Comments

Looks like it could be achieved by a group_by one-liner
Careful, result_date_hash = Hash.new([]) is almost never what you want, that only works here because you use a += e to add elements to the arrays and += makes copies of a. You really should say result_date_hash = Hash.new { |h, k| h[k] = [] }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.