Ruby: how does constant-lookup work in instance_eval/class_eval?

荒凉一梦 提交于 2019-12-01 09:13:37

In 1.9.2 the constant lookup has changed again to be equivalent to the 1.8.7 behavior.

class A
  class B
    class C
    end
  end
end

A.class_eval { B } # => NameError
A.instance_eval { B } # => NameError
A.new.instance_eval { B } # => A::B

Basically, the constants are quasi-lexically scoped. This USED to be different between 1.9.x and 1.8.x branches, and it made library cross compatibility a pain, so they changed it back.

Yehuda Katz's (successful) appeal to restore 1.8 behavior

Constants are effectively lexically scoped so you cannot access them short hand outside of the module hierarchy within which they are defined. There is a good explanation here and slightly off topic but a good read here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!