1

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).

4
  • 1
    Could you post actual Ruby code? Commented Nov 5, 2014 at 22:34
  • Please all give an example of the array, with as few elements as needed for the question, and the desired output. Commented Nov 5, 2014 at 23:00
  • If you are retrieving these from a database, why not simply iterate over the months and pull them by month? Commented Nov 5, 2014 at 23:06
  • Sorry about posting pseudocode instead of actual code before. I thought it would be more useful. Commented Nov 5, 2014 at 23:07

1 Answer 1

3

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

2 Comments

That's what I needed. Strangely, the "ruby/array" api page doesn't mention "group_by".
That's because it's here: Enumerable#group_by. If you're not familiar with the class Enumerable, have a browse. Those methods can be used with all types of collections (e.g., arrays, hashes, ranges, sets and others).

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.