gpt4 book ai didi

ruby - 如何在 Ruby 中取消定义命名空间类?

转载 作者:行者123 更新时间:2023-12-03 23:23:28 25 4
gpt4 key购买 nike

我可以取消定义 Bar ( How to undefine class in Ruby? ),但是如何取消定义 Foo::Bar ?

irb(main):266:0> Object.send :remove_const, :ActiveRecord::Base
TypeError: :ActiveRecord is not a class/module

irb(main):267:0> Object.send :remove_const, :"ActiveRecord::Base"
NameError: `ActiveRecord::Base' is not allowed as a constant name

irb(main):269:0> module ActiveRecord; Object.send :remove_const, :Base; end
NameError: constant Object::Base not defined

最佳答案

常量在它们各自的父模块中定义,顶级常量在 Object 中定义。类(class)。

因此,ActiveRecord::Base是在 Base 上定义的常数 (ActiveRecord)模块。现在,为了删除这个常量,你必须调用 remove_const ActiveRecord 上的方法模块:

ActiveRecord.send(:remove_const, :Base)

或者,您也可以直接从 Object 遍历路径。 , IE。
Object.const_get(:ActiveRecord).send(:remove_const, :Base)

关于ruby - 如何在 Ruby 中取消定义命名空间类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30348581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com