Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何自动创建目录中每个类的实例?_Ruby_Arrays_Oop_Class_Directory - Fatal编程技术网

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

Ruby 如何自动创建目录中每个类的实例?,ruby,arrays,oop,class,directory,Ruby,Arrays,Oop,Class,Directory,如何在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_fil

如何在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)

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

只是好奇你为什么要这么做?。。。这纯粹是学术性的吗?或者您希望预缓存项吗?不,我这样做是因为我不需要返回代码将类添加到预定义数组中。我相信,它将降低工作量,就像简单地将类中的文件放到目录中,让脚本完成困难的部分一样。您的答案包含Ruby中不典型的代码。蛇型文件通常是首选,因此
文件名
应该是
文件名
objects[object.length]=eval…
看起来像PHP,如果它是
objects@gmalette,那会更好,谢谢你。奇怪的是,我最近才开始用PHP进行开发,我在Ruby中工作的时间更长。有趣的解决方案,从来没有想到过。非常感谢。