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?
DateTime is considered deprecated. It only still exists to be backwards-compatible. As of Ruby 3 (released December 24th, 2020, as is Ruby tradition), DateTime only exists for backwards-compatibility. The date library docs recommend you just use Time instead.
Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.
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.
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.
Partial answer: it seems that the incomplete Date
class comes from irb, not from ruby.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With