日期类在Ruby 2.0中的错误行为
Ruby版本:日期类在Ruby 2.0中的错误行为,ruby,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 (NoMethodErro
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)
上面版本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(在评论部分)所指出的
这是因为Ruby 2.0有一个空的Date类来实现兼容性 原因 参考:
这是因为出于兼容性原因,Ruby 2.0有一个空的
Date
类。请看这里:@MarekLipka我已将您的答案发布为“社区维基”答案-如果您希望为您的答案赢得声誉积分,请将您的条目发布为答案,我将接受
p d = Date.new # uninitialized constant Date (NameError)
p Date.gregorian_leap?(2016) # did not reach here, previous line errored out