gpt4 book ai didi

ruby - 实例化类并推送到数组 Ruby

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:39 25 4
gpt4 key购买 nike

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

最佳答案

试试这个方法:

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

或使用eval:

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

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

关于ruby - 实例化类并推送到数组 Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com