ruby - Ruby 2.0 中的日期类行为异常

标签 ruby

Ruby 版本:ruby 2.0.0p247 (2013-06-27) [x64-mingw32]

为什么下面的代码能够创建 Date 对象但无法对其调用有效方法?

代码版本 1

p d = Date.new  # Works fine - Prints - #<Date:0x000000027aa628>
p Date.gregorian_leap?(2016) # undefined method `gregorian_leap?' for Date:Class (NoMethodError)

代码版本 2 如果我们添加 require 语句,上面的代码可以正常工作

require 'date'
p d = Date.new  # Prints #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>
p Date.gregorian_leap?(2016) # Prints true

在上面的版本 1 中实例化了哪个 Date 类? Ruby 是否有完全限定类名的概念,我们可以通过检查来找出两种情况下的区别?


Ruby 版本:ruby 2.2.2p95(2015-04-13 修订版 50295)[x64-mingw32]

Ruby 2.2 中,Date.new 提前失败 - 不像 Ruby 2.0 那样行为不端

p d = Date.new # uninitialized constant Date (NameError)
p Date.gregorian_leap?(2016) # did not reach here, previous line errored out

最佳答案

正如 Marek Lipka(在评论部分)所指出的,

It's because Ruby 2.0 had an empty Date class for compatibility reasons.

Reference: bugs.ruby-lang.org/issues/9890

关于ruby - Ruby 2.0 中的日期类行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31959755/

相关文章:

ruby - 是否可以使用 MiniTest 测试类方法(例如 Foo.bar)?

ruby - 如何在 Ruby 中分块数组

ruby-on-rails - 在firefox中网站被重定向到 "https"(其他浏览器正常)

ruby-on-rails - Bundler 找不到 gem "multi_json"的兼容版本

ruby - 破解 rails.vim 以与 Padrino 一起工作

ruby 1.9.2 + FreeBSD

ruby-on-rails - 无方法错误 : undefined method `fetch' for "QLite version 3.x":String

ruby-on-rails - rails 3 单元测试未运行

ruby - Rails Foxy Fixtures 抛出未知列错误

ruby - 不同环境的 Gemfile 依赖