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

use*_*719 3 ruby arrays oop directory class

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

先感谢您!

gma*_*tte 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)
Run Code Online (Sandbox Code Playgroud)