Victor Ribeiro
Victor Ribeiro

Reputation: 628

Ruby: Split / Sort array based on condition

I have an array of holidays:

Holiday.all                        
Holiday Load (0.7ms)  SELECT "holidays".* FROM "holidays"
=> #<ActiveRecord::Relation [#<Holiday id: 1, name: "Dia da Confraternização Universal", holidayable_id: 1, holidayable_type: "Country", date: "2014-01-01", created_at: "2014-11-05 21:38:13", updated_at: "2014-11-05 21:38:13", verified?: false>, #<Holiday id: 2, name: "Natal", holidayable_id: 1, holidayable_type: "Country", date: "2014-12-25", created_at: "2014-11-05 22:02:33", updated_at: "2014-11-05 22:02:33", verified?: false>]> 

I'd like to split this big array of dates by it's dates months, so I'd end up with 12 arrays (one for each month).

Upvotes: 1

Views: 1212

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176412

What you want to use is the Enumerable#group_by method.

Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.

If no block is given an enumerator is returned.

(1..6).group_by { |i| i%3 }   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}

For instance

["12/25", "01/01", (...)].group_by { |date| date.split("/").first } 

Upvotes: 3

Related Questions