简体   繁体   English

Ruby-remove_const:文件

[英]Ruby - remove_const :File

What is this piece of code doing? 这段代码在做什么?

class Object
   remove_const :File
end

Is it completely deleting[1] the class? 它会完全删除[1]类吗? When I call File.instance_methods after that piece of code, it's just showing the methods that are inherited from Object/Kernel. 当我在那段代码之后调用File.instance_methods ,它只是显示从对象/内核继承的方法。

Is it possible to revert this to original state? 是否可以将其还原为原始状态? I mean, after using remove_const , is there a way to bring the class back to it's original state? 我的意思是,在使用remove_const ,是否有办法将类恢复为原始状态? (without saving the class definition previously.) (不保存以前的类定义。)

[1] sorry for using the word "delete" [1]很抱歉使用“删除”一词

according to documentation: http://apidock.com/ruby/Module/remove_const 根据文档: http : //apidock.com/ruby/Module/remove_const

" Predefined classes and singleton objects (such as true) cannot be removed. " 无法删除预定义的类和单例对象(例如true)。

So this method will do nothing with File class. 因此,此方法对File类无效。 That is why you can use instance_methods on File . 这就是为什么您可以在File上使用instance_methods原因。 Class File still exists. 类文件仍然存在。

When you remove some class then you have to load it one more time (or run code of this class) if you want to use it again. 删除某个类后,如果要再次使用它,则必须再加载一次(或运行该类的代码)。

Important Edit : That was theory but practice shows (what undur_gongor and Andrew Grimm pointed out in the comments) that with both Ruby 1.8.7 and Ruby 1.9.2, we will get "uninitialized constant File". 重要说明 :这只是理论,但实践证明(在注释中undur_gongor和Andrew Grimm指出了什么),对于Ruby 1.8.7和Ruby 1.9.2,我们将获得“未初始化的常量文件”。 So documentation is misleading in this case... 因此在这种情况下文档会产生误导性...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM