Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 392
Ecnalyr Avatar asked Nov 18 '25 20:11

Ecnalyr


1 Answers

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!

like image 194
MrYoshiji Avatar answered Nov 21 '25 09:11

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!