Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
Get the first Monday of every quarter in Rails

What is the cleanest way to get the first Monday of every quarter of the year in Ruby on Rails?

The solutions i found looks terrible to me: Check if today is one of the first 7 days of the month, then check if today is Monday and finally look if this month is included in one of the 4 months of the quarter.

I think it should be a better way to accomplish this.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Here's my approach:

first_day = Date.today.beginning_of_year
mondays = 4.times.map do |i|
  first_day_of_quarter = first_day.advance(months: 3 * i).beginning_of_quarter
  first_day_of_quarter.monday? ? first_day_of_quarter : first_day_of_quarter.next_week
end

# [0] Mon, 04 Jan 2021,
# [1] Mon, 05 Apr 2021,
# [2] Mon, 05 Jul 2021,
# [3] Mon, 04 Oct 2021
over 4 years ago · Santiago Trujillo Denunciar

0

Here is a pure-Ruby solution.

def first_monday_by_quarter(year)
  [1, 4, 7, 10].map do |month|
    d = Date.new(year, month, 1)
    d.wday.zero? ? (d+1) : d+8-d.wday
  end
end
first_monday_by_quarter(2022)
  #=> [#<Date: 2022-01-03 ((2459583j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2022-04-04 ((2459674j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2022-07-04 ((2459765j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2022-10-03 ((2459856j,0s,0n),+0s,2299161j)>]
first_monday_by_quarter(Date.today.year)
  #=> #<Date: 2021-01-04 ((2459219j,0s,0n),+0s,2299161j)>,
  #   #<Date: 2021-04-05 ((2459310j,0s,0n),+0s,2299161j)>,
  #   #<Date: 2021-07-05 ((2459401j,0s,0n),+0s,2299161j)>,
  #   #<Date: 2021-10-04 ((2459492j,0s,0n),+0s,2299161j)>]

If desired, one could shorten Date.new(year, month, 1) to Date.new(year, month). require 'date' would be needed if this were used in pure-Ruby code.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda