Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Obtenga el primer lunes de cada trimestre en Rails

¿Cuál es la forma más limpia de obtener el primer lunes de cada trimestre del año en Ruby on Rails?

Las soluciones que encontré me parecen terribles: verifique si hoy es uno de los primeros 7 días del mes, luego verifique si hoy es lunes y finalmente verifique si este mes está incluido en uno de los 4 meses del trimestre.

Creo que debería ser una mejor manera de lograr esto.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Aquí está mi enfoque:

 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 Report

0

Aquí hay una solución de Ruby puro.

 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)>]

Si lo desea, se podría acortar Date.new(year, month, 1) a Date.new(year, month) . Se require 'date' si se usara en código Ruby puro.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!