23

In Ruby, I'd expect that a class which has not been required would raise an "uninitialized constant" error. This is the case with CSV, for instance.

However, Date behaves strangely: it is available, but apparently does not work, until it is required.

~: irb                                                                                             
>> Date.new(2012,7,24)
ArgumentError: wrong number of arguments(3 for 0)
>> require 'date'
=> true
>> Date.new(2012,7,24)
=> #<Date: 2012-07-24 ((2456133j,0s,0n),+0s,2299161j)>

What explains this behavior?

Nathan Long
  • 122,748
  • 97
  • 336
  • 451
  • 2
    +1, always bugged me. you'll notice the slight difference when calling `Date.ancestors` before and after the `require`. Also, calling `Date.new` (no args) before requiring seems to return a pretty generic object with no specific methods or instance variables. Guess it's somehow needed by the core classes ? – m_x Jul 24 '12 at 13:49

3 Answers3

10

I believe that date doesn't come from irb, but from rubygems, specifically the file where Gem::Specification is defined:

class Date; end # for ruby_code if date.rb wasn't required

I believe they needed any Date class defined so that the interpreter doesn't complain further down in the Specification class.

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
  • This seems like the more likely correct answer since the same behavior can be observed in pry, and nobody has yet pointed to the class definition in the irb source. Thanks! – Gabe Kopley Jan 29 '13 at 18:19
  • 1
    One should probably point out, that [`rubygems` is loaded automatically](http://stackoverflow.com/a/21531923/52499). – x-yuri May 14 '14 at 11:55
5

Similar to this question. irb loads a Date class by default, but Ruby itself doesn't (try e.g. puts Date.new in a file).

It seems that the Date class that irb loads is different to the distribution class, as you have pointed out. Furthermore this only seems to be the case in Ruby 1.9 -- if I try it in 1.8, I get the same class methods before and after the require.

Community
  • 1
  • 1
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
3

Partial answer: it seems that the incomplete Date class comes from irb, not from ruby.

m_x
  • 12,357
  • 7
  • 46
  • 60