How do I create automatically a instance of every class in a directory?

前端 未结 2 1513
失恋的感觉
失恋的感觉 2021-01-14 05:45

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条回答
  •  渐次进展
    2021-01-14 06:20

    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
    

提交回复
热议问题