If I load x.rb, then all the classes in that file are loaded. Is it possible to check and see what classes are being used and load those only?Assuming x.rb contains both Hello and Goodbye classes, and my program only uses the Hello Class, is it possible to load only the Hello Class?Happy with a script that checks the document, and outputs an .rb that has only the Hello Class and the code that uses it... Would be an interesting github project if doesn't exist, but I think it's out of my skillset atm. 解决方案 When classes are defined in their own separate file, you could use the autoload¹² method:autoload :Hello, 'x/hello'autoload :Goodbye, 'x/goodbye'When you write Hello, you are actually accessing the Hello constant. autoload uses const_missing to automatically require a file if the constant is not defined.Note that we are still dealing with files here. The contents of x/hello.rb will simply be read and evaluated. That code can run any operation. It can require other files. It could define a million other classes.That's because source code is really just text. This is especially true for interpreted languages. For example, in Java, you can usually only declare one public type per "compilation unit". In Ruby, there is no such thing.¹ Matz strongly discourages the practice² Ruby Inside article on autoload 这篇关于仅加载Ruby中正在使用的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-29 05:30
查看更多