nathanielelliott
nathanielelliott

Reputation: 67

Finding which date comes first of the next week - Ruby on Rails

I need to define which comes first before I run the def. I have to rake a file and set the date for the coming week BUT that date could be either Monday or Wednesday. I've gotten it thus far but not sure how to judge which date to use in this. I need to use whatever date comes first.

require 'date'

def date_of_next(day1, day2)
  day = day1
  date  = Date.parse(day)
  delta = date >= Date.today ? 0 : 7
  date + delta
end

hello = date_of_next("Monday", "Wednesday")
puts hello

The Problem: If I am on Saturday, I need to get the date for the coming "Monday". But, if I am on Tuesday, I need to get the date of "Wednesday". When I have the task finalized, it will run daily getting this information.

Upvotes: 0

Views: 737

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110725

Would this meet your requirements?

require 'Date'
def date_of_next(early_dow, late_dow)
  early_date = Date.parse(early_dow)
  late_date = Date.parse(late_dow)
  today = Date.today
  if today <= early_date
    early_date
  elsif today <= late_date
    late_date
  else
    early_date + 7
  end
end      

Upvotes: 0

Bala
Bala

Reputation: 11264

require 'date'

def date_of_next(d)
  Date.today.step(Date.today + 7).select{ |i| puts i if i.strftime("%A") == "#{d}" && i > Date.today} 
end

Upvotes: 0

AndyV
AndyV

Reputation: 3741

How about this?

require 'Date'

def date_of_next(*day_names)
  weekdays = day_names.map{|dayname| Date::DAYNAMES.index(day_name) }
  Range.new(Date.today, Date.today+6).detect{|day| weekdays.include? day.wday }
end

Here we're globbing the input allowing you to detect one or more weekday names. The first line finds the index of the name of the weekday in the Date::DAYNAMES array. In the second line we process up to a week's worth of dates returning when the first day.wday (weekday index) matches one of the weekdays we're looking for.

Upvotes: 0

Stefan
Stefan

Reputation: 114218

You code is based on https://stackoverflow.com/a/7930553/477037:

def date_of_next(day)
  date  = Date.parse(day)
  delta = date > Date.today ? 0 : 7
  date + delta
end

The above method returns the date for a single day. To find the first date for multiple days, call it for each day and find the first one (by sorting the dates):

def first_date_of_next(*days)
  days.map { |day| date_of_next(day) }.sort.first
end

first_date_of_next("Monday", "Wednesday")
#=> #<Date: 2013-10-16 ((2456582j,0s,0n),+0s,2299161j)>

Upvotes: 1

Related Questions