Get the last Friday day of every month

I'm new to ruby ​​and I want to get the last Friday day of every month. For example, the last Friday of March is 29, and the last Friday is April 26. So how can I get a solution? I am using rails framework.

The .cweek method returns the week of the year, but does not return the week of the current month.

+7
source share
4 answers
 #!/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 ..)

+8
source

I will go with Lee, answer, I am only posting this because (I thought) it is 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 
+4
source

Getting the last Friday of the month can be done in one 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 can use it as follows:

 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)>] 
+2
source
 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 
+1
source

All Articles