raphael_turtle
raphael_turtle

Reputation: 7314

Group ruby array in rails by year and month

I currently sort my events like;

@events_by_month = @events.group_by { |x| x.date.month }

this relied on the fact that all events occurred in the same year, however I now want to show events from next year too. I'd like the output in the same format as what the above outputs but sorted by year i.e this is what I have;

{3=>[#<Event id: 7032, date: "2014-03-02 00:00:00">, #<Event id: 7033, date: "2015-03-02 00:00:00">]}

and this is what I'd like;

{3=>[#<Event id: 7032, date: "2014-03-02 00:00:00">]},{3=> [#<Event id: 7033, date: "2015-03-02 00:00:00">]}

Upvotes: 2

Views: 1389

Answers (3)

Victor Moroz
Victor Moroz

Reputation: 9225

Assuming that events are sorted (sort_by(&:date)):

@events.group_by { |e| e.date.year } \
       .values \
       .map { |es| 
         es.group_by { |e| e.date.month } 
       }

Upvotes: 0

alex
alex

Reputation: 3742

You want to group events by month and year as I understood. Then use @events_by_month = @events.group_by { |x| [x.date.month, x.date.year] } you'll receive

{[3, 2014]=>[#<Event id: 7032, date: "2014-03-02 00:00:00">]},{[3,2015]=> [#<Event id: 7033, date: "2015-03-02 00:00:00">]}

It will be more correct then duplicated keys in your example.

Upvotes: 4

xlembouras
xlembouras

Reputation: 8295

I think this will work for you

results = []

@events.group_by { |x| x.date.year }.sort.
  each { |_, e| results << e.group_by { |x| x.date.month } }

example

[
  #<Event:0x007fd957d3dd98 @date=2014-03-02 21:37:18 +0200>,
  #<Event:0x007fd957d6e9e8 @date=2014-01-01 00:00:00 +0200>,
  #<Event:0x007fd957da4228 @date=2014-03-01 17:52:12 +0200>,
  #<Event:0x007fd957db98f8 @date=33702-11-27 23:25:40 +0200>
]

will give

[
  {
    3=>[#<Event:0x007fd957d3dd98 @date=2014-03-02 21:37:18 +0200>,
        #<Event:0x007fd957da4228 @date=2014-03-01 17:52:12 +0200>],
    1=>[#<Event:0x007fd957d6e9e8 @date=2014-01-01 00:00:00 +0200>]
  },
  {
    11=>[#<Event:0x007fd957db98f8 @date=33702-11-27 23:25:40 +0200>]
  }
]

Upvotes: 0

Related Questions