Skip to content

Commit 95dc00d

Browse files
committed
Add Get The Names Of The Month as a Ruby TIL
1 parent ece12aa commit 95dc00d

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1665 TILs and counting..._
13+
_1666 TILs and counting..._
1414

1515
See some of the other learning resources I work on:
1616

@@ -1358,6 +1358,7 @@ If you've learned something here, support my efforts writing daily TILs by
13581358
- [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md)
13591359
- [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md)
13601360
- [Get Specific Values From Arrays And Hashes](ruby/get-specific-values-from-hashes-and-arrays.md)
1361+
- [Get The Names Of The Month](ruby/get-the-names-of-the-month.md)
13611362
- [Get The Output Of Running A System Program](ruby/get-the-output-of-running-a-system-program.md)
13621363
- [Get UTC Offset For Different Time Zones](ruby/get-utc-offset-for-different-time-zones.md)
13631364
- [Identify Outdated Gems](ruby/identify-outdated-gems.md)

ruby/get-the-names-of-the-month.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Get The Names Of The Month
2+
3+
Ruby's `Date` object has a `MONTHNAMES` constant that returns an array of names
4+
of the month. You'd think that means the array contains 12 items. However, the
5+
size of that array is 13.
6+
7+
```ruby
8+
> Date::MONTHNAMES
9+
=> [nil, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
10+
```
11+
12+
Notice it has all 12 months, plus an initial value of `nil`.
13+
14+
This is because it allows us to more intuitive access a month by it's index
15+
without having to do a little subtraction. If I want to know what the 9th month
16+
is, I can do an array access for `9`.
17+
18+
```ruby
19+
> Date::MONTHNAMES[9]
20+
=> "September"
21+
```
22+
23+
Because arrays in Ruby use 0-based indexing, without this baked in `nil` value,
24+
you'd instead get `"October"` when passing in `9`.

0 commit comments

Comments
 (0)