Alex Alex - 6 months ago 9
Ruby Question

How to find the date number given the Year, month, day of the week and the week it falls on in ruby

So i'm new to ruby and not to familiar with the syntax of the Date gem, but is there a way to find the date of a moving holiday like fathers day?

So my current class for the moving holidays looks like this:

class MovingHoliday < Holiday
def initialize (name, month, day_of_week, week, year=2016)
@name = name
@month = month
@day_of_week = day_of_week
@week = week
@year = year
@my_date = Date.new(year, month, day)
end
end


and my input looks like this:

fathers_day = MovingHoliday.new("Fathers Day", 6, "sunday", 4, year)


The 6 is the month, "sunday" is well the day_of_the_week, and 4 is the week it falls on.
I just can't figure out the syntax if there is any that would/could do conversion for this.
And I can't use any gems other then rubys Date.

Answer
class MovingHoliday < Holiday
    def initialize (name, month, day_of_week, week, year=2016)
        @name = name
        @month = month
        @day_of_week = day_of_week
        @week = week
        @year = year
        @my_date = Date.new(year, month, 1)
        @my_date += 1 while !my_date.send("#{day_of_week}?")
        @my_date += (7 * (week - 1))
    end  
end

Not pretty, but it works. It takes the first of the month, moves up a day until it's the correct day of the week, and then increases by the appropriate number of weeks.

As it stands, it assumes that you're given an actual day of the week. You'll probably want to sanitize the input in some manner or convert from "sunday" to 0 (my_date.wday returns 0 for sunday, 1 for monday, etc)

Comments