实例化类并推送到数组Ruby

时间:2017-06-17 15:46:10

标签: ruby class loading

我正在尝试实例化场景目录中的所有类,并将它们添加到我的场景数组中。到目前为止,代码看起来应该可以工作,但我得到一个奇怪的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

这是我得到的关于regexp的语法错误,这只在我尝试运行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>'

2 个答案:

答案 0 :(得分:3)

尝试这种方法:

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

eval

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

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

答案 1 :(得分:1)

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

/scenes/ct.new()

这是非法Regexp字面值,与

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

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