Cassidoo's Interview question of the week | 442

Hey everyone! :waving_hand:

Hope you’re all doing great!

You might know Cassidy Williams – she’s been publishing her awesome newsletter for years now, and each issue includes a fun interview question to solve.

Here’s the idea: solve it in Ruby, share your solution with her, and then drop it here too! It’s a great way to learn from each other, get inspired by different approaches, and have some good discussions.

To keep things tidy, I’ll be sharing a new question here each week. Feel free to follow along!

This week’s question:
February 2026 is a perfect month! Write a function that returns the closest previous and next perfect month around the given Gregorian year.

Examples:

nearestPerfectMonths(2025)
> { prev: "2021-02", next: "2026-02" }

nearestPerfectMonths(2026)
> { prev: "2026-02", next: "2027-02" }

Happy coding :heart:

4 Likes

My solution:

require 'date'

def find_nearest_perfect_months(year)
  prev_year = year - 1
  prev_year -= 1 until perfect_february?(prev_year)

  next_year = year + 1
  next_year += 1 until perfect_february?(next_year)

  { prev: "#{prev_year}-02", next: "#{next_year}-02" }
end

def perfect_february?(y)
  !Date.leap?(y) && [0, 1].include?(Date.new(y, 2, 1).wday)
end

p find_nearest_perfect_months(2025)
2 Likes

perfect = ->(y) { Date.new(y, 2, 1).wday == week_start && !Date.leap?(y) } # week_start can be 0 or 1 and then usual

prev_y = year.downto(year - 11).find(&perfect)

i would do something like above:)

4 Likes

TIL Numeric#step!

require "date"

def perfect_february?(year)
  return false if Date.leap?(year)

  february_1 = Date.new(year, 2, 1)
  february_1.sunday? || february_1.monday?
end

def nearest_perfect_months(year)
  prev_year = year.step(by: -1).find { perfect_february? it }
  next_year = (year + 1).step.find { perfect_february? it }

  {prev: "#{prev_year}-02", next: "#{next_year}-02"}
end

# Tests

nearest_perfect_months(2025).then do
  puts it
  raise unless it == {prev: "2021-02", next: "2026-02"}
end

nearest_perfect_months(2026).then do
  puts it
  raise unless it == {prev: "2026-02", next: "2027-02"}
end
3 Likes