如何在ruby中为目录中的每个文件中的每个类创建一个实例
以数组的形式提供?
提前谢谢你!
最佳答案
您可以使用ObjectSpace
找到新类,然后将它们实例化。
def load_and_instantiate(class_files)
# Find all the classes in ObjectSpace before the requires
before = ObjectSpace.each_object(Class).to_a
# Require all files
class_files.each {|file| require file }
# Find all the classes now
after = ObjectSpace.each_object(Class).to_a
# Map on the difference and instantiate
(after - before).map {|klass| klass.new }
end
# Load them!
files = Dir.glob("path/to/dir/*.rb")
objects = load_and_instantiate(files)