We create positive world change connecting authentic companies with real people in socially responsible ways.

Unicorn

How to Get a Month Name from a Month Number in Ruby

June 08, 2010 by Brandon Weiss

Today I had a need to get the name of a month by its number. So if I had the number ‘6’ I would want to be able to get ‘June’.

This is not a particularly complicated problem; there are myriad ways to accomplish this, but all of them are rather kludgey, and Ruby being such a magical language I was sure there must be a method built-in. Or at the very least there would be a helper for it in Rails.

But after checking the docs for both I couldn’t find anything. Google also returned nothing except the kludgey ways I already knew how to do. So I gave up and wrote this:

month = 06
date = Date.parse("2010-#{month}-01")
month_name = date.strftime("%B") # => "June"

As I said it’s very simple to do, but seems so unnecessarily roundabout. Parsing a string to a Date object and then using the date formatter method to get the name? That doesn’t smell anything like Ruby.

I could create my own array or hash to map them, which is slightly more elegant, but more lines of code, and still rather roundabout.

So I took one more look at the docs, and while I was reading them it occurred to me that if the strftime method can do it, Ruby must have some internal way of mapping month numbers to names. So I took a look at the actual source for strftime and found the answer.

Although I’ve been to the doc page for the Date class hundreds of times, I’d never really used it except to reference particular methods, so I’ve always just skipped right by the constants section at the beginning. But in it there’s a MONTHNAMES constant, and on the first line in the section, no less.

So to get the month name from a number, all you have to do is1:

Date::MONTHNAMES[6] # => "June"

Ruby really is made out of unicorns.

1 As an added bonus, since arrays start with 0, they’ve shifted the array values up one by starting the array with nil at index 0, so you can get the actual month name of a number without having to manually subtract 1 from that number.

Comments

image placeholder