Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Date exist in Ruby before it is required?

Tags:

date

ruby

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?

like image 945
Nathan Long Avatar asked Jul 24 '12 13:07

Nathan Long


People also ask

Is DateTime deprecated Ruby?

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.

How do you parse time in Ruby?

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.


3 Answers

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.

like image 126
Mladen Jablanović Avatar answered Sep 19 '22 17:09

Mladen Jablanović


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.

like image 44
Lars Kotthoff Avatar answered Sep 22 '22 17:09

Lars Kotthoff


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

like image 25
m_x Avatar answered Sep 21 '22 17:09

m_x