为什么 Ruby 的 Date 类会自动加载而 DateTime 不会?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9704969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is Ruby's Date class automatically loaded but DateTime is not?
提问by Kamilski81
Using IRB, why are the Date & Time classes automatically loaded, but DateTime is not? I have to require 'date', this does not make sense to me because I thought that both Date and DateTime were using the standard library 'date'?
使用 IRB,为什么 Date & Time 类会自动加载,而 DateTime 不会?我必须require 'date',这对我来说没有意义,因为我认为 Date 和 DateTime 都在使用标准库'date'?
ruby-1.9.2-p290 :001 > Date
=> Date
ruby-1.9.2-p290 :002 > Time
=> Time
ruby-1.9.2-p290 :003 > DateTime
NameError: uninitialized constant Object::DateTime
from (irb):3
from /Users/kamilski81/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'
ruby-1.9.2-p290 :004 > require 'date'
=> true
ruby-1.9.2-p290 :005 > require 'date'
=> false
ruby-1.9.2-p290 :006 > DateTime
=> DateTime
采纳答案by Kamilski81
Being a little more curious, I tried:
出于好奇,我尝试了:
$ ruby -e 'puts DateTime.class'
-e:1:in `<main>': uninitialized constant Object::DateTime (NameError)
[~, kamilski81@mac]
$ ruby -e 'puts Date.class'
-e:1:in `<main>': uninitialized constant Object::Date (NameError)
$ ruby -e 'puts Time.class'
Class
So it makes me think that it's an irb issue that automatically loads 'date'.
所以这让我觉得这是一个自动加载“日期”的irb问题。
回答by TekuConcept
In IRB, include this line: require 'date'then you will be able to use DateTime.
在 IRB 中,包括这一行:require 'date'然后您将能够使用 DateTime。
irb(main):000:0> DateTime.class
NameError: uninitialized constant DateTime
from (irb):0
from /path/to/ruby/irb:12:in '(main)'
irb(main):001:0> require 'date'
=> true
irb(main):002:0> DateTime.class
=> Class
回答by Nomis
Worked for me when first initializing with require 'date'.
首次使用require 'date'.

