如何自动创建一个目录中所有类的实例?(How do I create automatically a

2019-06-26 07:03发布

我如何在红宝石在一个目录中的每个文件创建的每一个类的实例,并提供它作为一个数组?

先感谢您!

Answer 1:

您可以使用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)


Answer 2:

假设他们都有着相同的名字作为自己含有.RB文件并没有参数初始化...

#initialize array of objects
objects = []

#list ruby files in directory
classes = Dir.glob( "*.rb" )

#make method to easily remove file extension
def cleanse( fileName )
    return fileName.gsub( ".rb", "" )
end

classes.each do |file|
    #require the new class
    require fileName

    #add it to our array
    objects[objects.length] = eval( cleanse(file) + ".new()" )
end


文章来源: How do I create automatically a instance of every class in a directory?