Ecnalyr
Ecnalyr

Reputation: 5802

How to group objects by every date within a range of dates

I can create a hash like this:

@time_offs_by_date = @time_offs.group_by{ |time_off| time_off.start_date}

Which I then iterate through using

@time_offs_by_date[date] # I am drawing a calendar date-by-date
# I then list details about every object grouped by the specified date

I would like to group my objects by every date included in the range between time_off.start_date and time_off.end_date.

How would I do this?

Upvotes: 3

Views: 1190

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

This should do it:

@time_offs_by_date = @time_offs.group_by{ |time_off| time_off.start_date..time_off.end_date }

@time_offs_by_date.each do |range, time_offs|
  # do your logic here
end

This will produce a Hash with Range objects as keys, and an array of TimeOff as values.

Documentation about the class Range (Ruby 1.9.3): http://www.ruby-doc.org/core-1.9.3/Range.html

Hope that helps!

Upvotes: 3

Related Questions