How to find the dates of the last Fridays of each month of a given year in Ruby

1 Answer

0 votes
require "date"

# Return all last Fridays of each month in a given year
def last_fridays_of_year(year)
  Enumerator.new do |yielder|
    (1..12).each do |month|

      # Last day of the month
      date = Date.new(year, month, 1) >> 1  # AddMonths(1)
      date = date - date.day                # AddDays(-1) to last day of previous month

      # Walk backward to Friday
      while date.wday != 5  # 5 = Friday
        date -= 1
      end

      yielder << date
    end
  end
end

year =
  if ARGV.length > 0
    ARGV[0].to_i
  else
    2026
  end

last_fridays_of_year(year).each do |date|
  puts date.strftime("%m/%d/%Y")
end



=begin
run:

01/30/2026
02/27/2026
03/27/2026
04/24/2026
05/29/2026
06/26/2026
07/31/2026
08/28/2026
09/25/2026
10/30/2026
11/27/2026
12/25/2026

=end

 



answered May 23 by avibootz

Related questions

...