I have to get all months names in order between two dates using Ruby. For example, I want to get:
['jan','feb','mars']
When I make a diff between:
1st january and March 15th
I also want it to work when the date diff is greater than one year.
Any idea?
I’d go with:
or:
which is probably a little faster.
The problem is the year boundary. You have to track years and months, not just the months, otherwise you’ll remove all the duplicated month indexes when using
uniqto remove the days. I went with theYYYYMMformat, to get the right granularity.EDIT:
Let’s make it even more interesting.
I had some code smell that kept bugging me. I didn’t like using
Date.strftimeandDate.strptime, so I took another run at the problem: Here are two more solutions that are running a lot faster, along with the benchmarks:With output looking like:
Interesting. “
rmb” is now running way behind. Pulling it from the tests and bumping up the loops 100x:Which gives:
It’s basically a tie between the two new ways of getting the months. Being anal, I’d go with
mb2because it’d be a little bit faster if I was doing this millions of times, but your mileage might vary.