patternrubyrailsMinor
Loop through months (1-12)
Viewed 0 times
loopmonthsthrough
Problem
I currently have this monstrosity:
I want to get the month that is
E.g. if
This works, but has that horrible
Any alternatives?
next_period = (((current_month + tax_period_months)-1) % 12) + 1I 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=12This works, but has that horrible
-1 +1 to stop month 12 becoming 0Any 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
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).monthCode Snippets
require 'date'
next_period = (Date.today >> tax_period_months).monthContext
StackExchange Code Review Q#140533, answer score: 6
Revisions (0)
No revisions yet.