实例化 class 并推送到数组 Ruby

Instantiate class and push to array Ruby

我正在尝试实例化场景目录中的所有 类 并将它们添加到我的场景数组中。到目前为止,代码看起来应该可以工作,但我收到一个奇怪的 rgexp -ct 错误,我无法在网上找到任何答案。这是我的代码

class Game
    @scenes = []

    def initialize
        Dir[File.dirname(__FILE__)+"/scenes/*.rb"].each do |file|
            require_relative file
            @scenes << eval("#{file.gsub(".rb", "")}.new()")
        end
    end
end

目录中的场景如下所示。我可以要求他们并看到文件名就好了。

class Scene99
    @number = 99
    @text = "This is the first scene."
    @next_scene = 0

    def initialize
        puts "WORKS"
    end
end

这是我得到的有关正则表达式的语法错误,这仅在我尝试 运行 eval(...

/Users/icetimux/projects/death-at-appledore-towers/lib/death-at-appledore-towers/game.rb:8:in `eval': (eval):1: unknown regexp options - ct (SyntaxError)
        from /Users/icetimux/projects/death-at-appledore-towers/lib/death-at-appledore-towers/game.rb:8:in `block in initialize'
        from /Users/icetimux/projects/death-at-appledore-towers/lib/death-at-appledore-towers/game.rb:6:in `each'
        from /Users/icetimux/projects/death-at-appledore-towers/lib/death-at-appledore-towers/game.rb:6:in `initialize'
        from death-at-appledore-towers.rb:3:in `new'
        from death-at-appledore-towers.rb:3:in `<main>'

好吧,如果你有一个名为 ct.rb 的文件,那么 file 将是 /scenes/ct.rb,你将 eval

/scenes/ct.new()

这是一个非法的Regexp字面量,与

相同
(/scenes/ct).new()

老实说,我什至不知道该代码应该做什么,所以我无法提供修复,但这就是问题所在。您盲目地假设任何文件名都是有效 Regexp 标志(例如 xm)的组合。

试试这个方法:

@scenes << file.split("/").last.gsub(".rb", "").camelize.constantize.new

或与eval

@scenes << eval("#{file.split("/").last.gsub(".rb", "").camelize}.new")

我假设该文件是一个类似于 './scenes/scene99.rb' 的字符串,并且您需要获取一组场景对象。