Reputation: 48
I want to get a flat array of dates in a date range for Items with many Bookings. A Booking has :start_date
and :end_date
.
example, Item has these bookings:
Booking A: 10/1/17 to 10/3/17
Booking B: 11/2/17 to 11/4/17
I tried using pluck. Item.bookings.pluck[:start_date, :end_date]
and it gives me an array that looks like this [["10,01,17", "10,03,17"], ["11,02,17" , "11,04,17" ]]
What I need is a flat array with the date ranges like this ["10,01,17", "10/02/17", "10,03,17", "11,02,17" , "11,03,17", "11/04/17"]
Upvotes: 2
Views: 1517
Reputation: 95242
Well, in order to get ranges, you need actual Date objects. To get those out of strings like yours, you'll need to use Date.strptime
. Then you can build Ranges out of the date pairs, and then convert back to strings with Date#strftime
:
require 'date'
format = '%m/%d/%y' # mm/dd/yy; adjust as needed
dates = Item.bookings.pluck(%i<start_date end_date>).map do |bounds|
Range.new(*bounds.map { |d| Date.strptime(d, format) }).map do |d|
d.strftime(format)
end
end.flatten
Which with your example data set gives me this:
["10/01/17", "10/02/17", "10/03/17", "11/02/17", "11/03/17", "11/04/17"]
Upvotes: 2