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

1 Answer

0 votes
require 'date'

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

      # Last day of the month
      date = Date.new(year, month, 1).next_month.prev_day

      # Walk backward to Sunday
      while date.wday != 0   # Sunday = 0
        date -= 1
      end

      yielder << date
    end
  end
end

# Main
args = ARGV
year = args.length > 0 ? args[0].to_i : 2026

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



=begin
run:

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

=end

 



answered 9 hours ago by avibootz

Related questions

...