简体   繁体   中英

Ruby - remove_const :File

What is this piece of code doing?

class Object
   remove_const :File
end

Is it completely deleting[1] the class? When I call File.instance_methods after that piece of code, it's just showing the methods that are inherited from Object/Kernel.

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? (without saving the class definition previously.)

[1] sorry for using the word "delete"

according to documentation: http://apidock.com/ruby/Module/remove_const

" Predefined classes and singleton objects (such as true) cannot be removed. "

So this method will do nothing with File class. That is why you can use instance_methods on File . 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". So documentation is misleading in this case...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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