Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda