Sippin' on Syntactic Sugar

proudly made here on earth

The Ruby Date Class: A Brief Lesson Learned

Why can I use the Ruby `Date` class without requiring date?

I was doing an exercism.io exercise, Gigasecond, which required me to address my fear of date and time. (You can see my submission here and nitpick if you’d like.)

I noticed that I could use date without actually requiring date.

I thought to myself, “hmmm, that seems awfully inefficient. Why should I type require 'date’ if I don’t need to?” So this caused an investigation into: Do I actually need to require ‘date’?

My first stop was irb, where I noticed that I would get different results depending on whether or not required date and further if I required date after the fact, the result would change too.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
date = Date.new
=> #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>

date.class
=> Date


require ‘Date’
new_date = Date.new
=> #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>

new_date.class
=> Date

date.class
=> uninitialized constant error/bug!

Suspicious.

I did the same exercise in repl.it and got an uninitialized constant error. I also did the same investigation for Time but there was no inconsistency in the results. So this led me to believe there was some versioning issue or perhaps there really is an bug in irb.

I posted on StackOverflow and got some good information.

Basically, it’s a Rubygems bug for Rubygems versions earlier than 2.4.0!

So, if you run gem environment in terminal you should see what version of ruby gems and ruby you’re running.

Apparently there is an intention to include this Rubygems fix into Ruby 2.2. So until then, you can update your version of Rubygems by:

1
2
$ gem install rubygems-update
$ update_rubygems

and voila! When you try to create a Date object without requiring date you should now get a uninitialized constant error.

Happy halloween.