From 95dc00d748544d27fea493e7ac4f15295eae7928 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 24 Oct 2025 15:18:40 -0500 Subject: [PATCH] Add Get The Names Of The Month as a Ruby TIL --- README.md | 3 ++- ruby/get-the-names-of-the-month.md | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 ruby/get-the-names-of-the-month.md diff --git a/README.md b/README.md index 755eb34..ba9b567 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1665 TILs and counting..._ +_1666 TILs and counting..._ See some of the other learning resources I work on: @@ -1358,6 +1358,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md) - [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md) - [Get Specific Values From Arrays And Hashes](ruby/get-specific-values-from-hashes-and-arrays.md) +- [Get The Names Of The Month](ruby/get-the-names-of-the-month.md) - [Get The Output Of Running A System Program](ruby/get-the-output-of-running-a-system-program.md) - [Get UTC Offset For Different Time Zones](ruby/get-utc-offset-for-different-time-zones.md) - [Identify Outdated Gems](ruby/identify-outdated-gems.md) diff --git a/ruby/get-the-names-of-the-month.md b/ruby/get-the-names-of-the-month.md new file mode 100644 index 0000000..d88f65d --- /dev/null +++ b/ruby/get-the-names-of-the-month.md @@ -0,0 +1,24 @@ +# Get The Names Of The Month + +Ruby's `Date` object has a `MONTHNAMES` constant that returns an array of names +of the month. You'd think that means the array contains 12 items. However, the +size of that array is 13. + +```ruby +> Date::MONTHNAMES +=> [nil, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] +``` + +Notice it has all 12 months, plus an initial value of `nil`. + +This is because it allows us to more intuitive access a month by it's index +without having to do a little subtraction. If I want to know what the 9th month +is, I can do an array access for `9`. + +```ruby +> Date::MONTHNAMES[9] +=> "September" +``` + +Because arrays in Ruby use 0-based indexing, without this baked in `nil` value, +you'd instead get `"October"` when passing in `9`.