Reputation: 670
I am new with ruby and I want to get the day of the last Friday of each month. For example, the last Friday of March is 29, the Last Friday of April 26. So, how can I get a solution? I'm using the rails framework.
The method .cweek
returns the week of the year, but does not return the week of the current month.
Upvotes: 9
Views: 4257
Reputation: 13574
Retrieving the last friday of a month can be made in a single line:
def last_fridays_for_every_month_of_year(year)
(1..12).map do |month|
Date.new(year, month, -1).downto(0).find(&:friday?)
end
end
You may use it like this:
last_fridays_for_every_month_of_year 2013
#=> [#<Date: 2013-01-25 ((2456318j,0s,0n),+0s,2299161j)>,
#<Date: 2013-02-22 ((2456346j,0s,0n),+0s,2299161j)>,
#<Date: 2013-03-29 ((2456381j,0s,0n),+0s,2299161j)>,
#<Date: 2013-04-26 ((2456409j,0s,0n),+0s,2299161j)>,
#<Date: 2013-05-31 ((2456444j,0s,0n),+0s,2299161j)>,
#<Date: 2013-06-28 ((2456472j,0s,0n),+0s,2299161j)>,
#<Date: 2013-07-26 ((2456500j,0s,0n),+0s,2299161j)>,
#<Date: 2013-08-30 ((2456535j,0s,0n),+0s,2299161j)>,
#<Date: 2013-09-27 ((2456563j,0s,0n),+0s,2299161j)>,
#<Date: 2013-10-25 ((2456591j,0s,0n),+0s,2299161j)>,
#<Date: 2013-11-29 ((2456626j,0s,0n),+0s,2299161j)>,
#<Date: 2013-12-27 ((2456654j,0s,0n),+0s,2299161j)>]
Upvotes: 3
Reputation: 16241
#!/usr/bin/env ruby
require 'date'
(1..12).each do |month|
d = Date.new(2013, month, -1)
d -= (d.wday - 5) % 7
puts d
end
Source (second/third Google result..)
Upvotes: 10
Reputation: 168091
require "active_support/core_ext"
end_of_month = Date.today.end_of_month
if end_of_month - end_of_month.beginning_of_week >= 4
end_of_month+5.days
else
end_of_month-2.days
end
# => Fri, 29 Mar 2013
Upvotes: 1
Reputation: 4471
I would go with Lee's answer, I'm only posting this one because (I thought) it's pretty cool.
Using gem Chronic
(https://github.com/mojombo/chronic):
#Last Friday of this coming December
require 'chronic'
last_friday = Chronic.parse("First Friday of next January") - 1.week
Upvotes: 4