How do I create automatically a instance of every

2019-02-18 13:17发布

How do I in ruby create an instance of every class in each file in a directory and providing it as an array?

Thank you in advance!

2条回答
混吃等死
2楼-- · 2019-02-18 13:39

Assuming that they all share the same name as their containing .rb file and take no arguments to initialize...

#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
查看更多
Animai°情兽
3楼-- · 2019-02-18 13:56

You can use the ObjectSpace to find the new classes and then instantiate them.

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)
查看更多
登录 后发表回答