为什么NameError在第二(而不是第一)位置的祖先中有NameError?

时间:2019-06-27 08:35:19

标签: ruby

尽管我试图完全理解NoMethodError和NameError之间的区别,但我发现NameError在祖先中不在0位置。是DidYouMean的魔法吗?

[1] pry(main)> NameError.ancestors
=> [DidYouMean::Correctable,
 NameError,
 StandardError,
 Exception,
 ActiveSupport::Dependencies::Blamable,
 ActiveSupport::ToJsonWithActiveSupportEncoder,
 Object,
 ActiveSupport::Dependencies::Loadable,
 PP::ObjectMixin,
 Nori::CoreExt::Object,
 JSON::Ext::Generator::GeneratorMethods::Object,
 ActiveSupport::Tryable,
 Kernel,
 BasicObject]

顺便说一句:对于不了解NoMethodErrorNameError之间的区别的人。当您尝试访问某些可能是局部变量的内容时引发NameError

(pry)> foo # this can be both - local variable or method => NameError
(pry)> Object.foo # this is 100% method => NoMethodError

1 个答案:

答案 0 :(得分:3)

  

DidYouMean有点神奇吗?

不,只是普通的红宝石。这就是您use prepend时发生的情况。

NameError.prepend DidYouMean::Correctable
KeyError.prepend DidYouMean::Correctable