HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Loop through months (1-12)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
loopmonthsthrough

Problem

I currently have this monstrosity:

next_period = (((current_month + tax_period_months)-1) % 12) + 1


I want to get the month that is tax_period_months after the current month.

E.g. if tax_period_months=3, and current_month=09 then next_period=12

This works, but has that horrible -1 +1 to stop month 12 becoming 0

Any alternatives?

Solution

If that really is all you need to calculate, then it's not too bad.

However, I suspect that you have other date calculations happening in your application. In that case, why not take advantage of Ruby's Date class? The >> operator adds months.

require 'date'
next_period = (Date.today >> tax_period_months).month

Code Snippets

require 'date'
next_period = (Date.today >> tax_period_months).month

Context

StackExchange Code Review Q#140533, answer score: 6

Revisions (0)

No revisions yet.