Prezes Łukasz
Prezes Łukasz

Reputation: 968

Getting dates for the nearest n day of week

I try to implement method, that return collection of dates for the nearest n day of week e.g. Monday.

My method:

  def date_of_next(day, weeks)
    date = Date.parse(day)
    if date > Date.today
      delta = 0
      date + delta
    else
      (0..weeks.to_i).each do |i|
        delta = 7 * i
        date + delta
      end
    end
  end

I don't have any idea to properly repair this method. Could you help me? Thanks in advance.

My prediction of return:

Code of select:

= f.select :date_of_training, label: "Data",
  collection: @trainer.work_schedules.map{ |tw| [tw.next_n_days(4, "Monday"), tw.id]},
  prompt: "Wybierz datę"

Result:

2016-05-16
2016-05-16
2016-05-30
2016-06-06

Upvotes: 0

Views: 51

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Naïve implementation:

def next_n_days(amount, day_of_week)
  (Date.today...Date.today+7*amount).select do |d|
    d.wday == day_of_week
  end
end

#     three ⇓  ⇓ Fridays
next_n_days 3, 5
#⇒ [
#   [0] #<Date: 2016-05-13 ((2457522j,0s,0n),+0s,2299161j)>,
#   [1] #<Date: 2016-05-20 ((2457529j,0s,0n),+0s,2299161j)>,
#   [2] #<Date: 2016-05-27 ((2457536j,0s,0n),+0s,2299161j)>
# ]

More accurate implementation:

def next_n_days(amount, day_of_week)
  nearest = (Date.today...Date.today+7).detect { |d| d.wday == day_of_week }
  nearest.step(nearest+7*amount-1, 7).to_a
end

Upvotes: 1

Related Questions