2

I recently was doing an exercism.io exercise to determine a person's gigagsecond anniversary, given her/his birthday. If you want, you can nitpick me here.

While doing this exercise, I discovered in irb that I get different results if I did not require 'date'. enter image description here

vs using require 'date'.

enter image description here

Further I tried the same in repl.it, and get an error if I try to use Date without require 'Date'.

enter image description here

I was able to find some responses to the 'uninitialized constant' error (Why is Ruby's Date class automatically loaded but DateTime is not? and Why does Date exist in Ruby before it is required?.) which led me down the path of perhaps versioning is the culprit; but, I couldn't find any overwhelmingly definitive response.

I am using: Ruby 2.1.3, irb 0.9.6 (which I believe uses Ruby 2.0.0) and repl.it is using Ruby 1.8.7(beta).

So, is this a version thing? ...an irb vs Ruby thing? ...a Date class in the standard library + Date module thing? Or simply that I'm just a n00b?

Lastly I messed around a bit more with the date objects in irb and got an error 'Maybe IRB bug!'enter image description here

(FWIW, I did the same thing for 'time' in irb but this time, got the same result regardless if I required 'time'.) enter image description here

Community
  • 1
  • 1
glamouracademy
  • 103
  • 2
  • 8

2 Answers2

1

Rubygems (which is required by default) defines a empty, non-functioning Date class in versions earlier than 2.4.0 (Rubygems version, not Ruby). This has been fixed recently (also see the Ruby bug report). The version of Rubygems with the fix will likely be included in Ruby 2.2.

matt
  • 78,533
  • 8
  • 163
  • 197
  • Thanks @matt! I [updated my version of Rubygems](https://rubygems.org/pages/download) to the most current version 2.4.2. And tested in irb without `require 'date'`: `2.1.3 :001 > date = Date.new` `NameError: uninitialized constant Date` ...and with: `2.1.3 :002 > require 'date' => true` `2.1.3 :003 > date = Date.new => #` – glamouracademy Oct 30 '14 at 14:19
0

This is not an IRB issue. At least in Ruby 2.1, require 'date' loads both the Date and DateTime classes. In fact, the second line of the Date doc states, "'date' provides two classes Date and DateTime."

File t.rb:

require 'date'
p DateTime.new(2014,01,01,01,01,01).to_time

Carys-MacBook-Pro:ruby_src Cary$ ruby "t.rb"

#=> 2013-12-31 17:01:01 -0800

It appears to also load the Time class as well:

p Date.today.to_time.to_a.join(' ')
#=>  "0 0 0 29 10 2014 3 302 true PDT"

though I suppose it could be that to_time loads Time. Can someone clarify this last point?

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100