Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a default Ruby Date object? [duplicate]

Tags:

date

class

ruby

Why are only some methods of the Date class loaded without an explicit:

require 'date'

line?

For example:

irb(main):002:0> Date.today
NoMethodError: undefined method `today' for Date:Class
from (irb):2
from /Users/mwlang/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'

And then...

irb(main):003:0> require 'date'
=> true

leads to...

irb(main):004:0> Date.today
=> #<Date: 2013-04-12 ((2456395j,0s,0n),+0s,2299161j)>

The documentation at http://ruby-doc.org/stdlib-2.0/libdoc/date/rdoc/Date.html seems to offer no explicit explanation for this behavior. Comments on #irc say its a stdlib rather than core library, but core doesn't even have Date class defined and launching irc with -f (suppress reading .irbrc) to get a minimal load still appears to load some sort of base/core Date class.

Would like a technical explanation of what's going on and references to the Ruby docs that explain this so I understand for other such encounters as I switch from Ruby 1.8.7 to Ruby 2.0.0.

like image 663
Michael Lang Avatar asked Apr 12 '13 13:04

Michael Lang


People also ask

How do I change the Date format in Ruby?

Two steps: You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.

How do you create a Date object in Ruby?

A Date object is created with Date::new , Date::jd , Date::ordinal , Date::commercial , Date::parse , Date::strptime , Date::today , Time#to_date , etc. require 'date' Date. new(2001,2,3) #=> #<Date: 2001-02-03 ...> Date.

How do I clone a DateTime?

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (epoch time): var date = new Date(); var copiedDate = new Date(date.


2 Answers

The Date class you are seeing is defined in lib/rubygems/specification.rb for compatibility reasons:

# date.rb can't be loaded for `make install` due to miniruby
# Date is needed for old gems that stored #date as Date instead of Time.
class Date; end

It's an empty class definition and it doesn't provide any methods or functionality.

If starting IRB without RubyGems, that Date class is gone:

$ ruby --disable-gems -S irb
irb(main):001:0> Date
NameError: uninitialized constant Date

Update

The empty Date class was removed in RubyGems 2.4.0:

  • RubyGems no longer defines an empty Date class. Pull Request #948 by Benoit Daloze.
like image 117
Stefan Avatar answered Oct 04 '22 19:10

Stefan


Complementing @Stefan answer:

Please note that This has been removed, in later version of rubygems.

  • Changelog here
  • Merge Request here
like image 24
astreal Avatar answered Oct 04 '22 19:10

astreal