如何自动创建目录中每个类的实例?

时间:2012-07-13 12:13:47

标签: ruby arrays oop class directory

我如何在ruby中创建目录中每个文件中每个类的实例 将它作为数组提供?

提前谢谢!

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

假设它们都与包含.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