我正在研究Ruby中的一个新型生成器(我的第一个项目),我正在为该生成器构建虚构的世界系统。我正在尝试使用我的设置构建类似目录的结构。因此,例如,我创建了一个“地球”设置,它包含“北美”,其中包含“美国”。
我现在正在做的方式,我用可选的超级设置初始化每个设置(否则它是零)然后我有一个add_setting方法创建一个新的自我设置作为超级并将其添加到数组全部跟踪。然后我很容易添加其他方法来上下链子找到父母和孩子。
def initialize(name, supersetting = nil,subsettings = [])
@name = name
@supersetting = supersetting
@subsettings = subsettings
end
def add_setting(name)
new_setting = Setting.new(name, self)
@subsettings.push(new_setting)
end
def tree
tree = []
setting = self
while !(setting == nil) do
tree.unshift(setting.name)
setting = setting.supersetting
end
tree
end
def all_subsettings
all = @subsettings
@subsettings.each do |sub|
all = all + sub.all_subsettings
end
all
end
earth = Setting.new("Earth")
earth.add_setting("North America")
earth.subsettings[0].add_setting("USA")
earth.subsettings[0].subsettings[0].add_setting("Virginia")
earth.subsettings[0].subsettings[0].add_setting("Washington, D.C.")
earth.subsettings[0].subsettings[0].subsettings[0].add_setting("Alexandria")
earth.subsettings[0].subsettings[0].subsettings[0].add_setting("Richmond")
earth.subsettings[0].subsettings[0].subsettings[1].add_setting("Georgetown")
p earth.see_all_subsettings
p earth.name_all_subsettings
产量
["Earth > North America", "Earth > North America > USA", "Earth > North America > USA > Virginia", "Earth > North America > USA > Washington, D.C.", "Earth > North America > USA > Virginia > Alexandria", "Earth > North America > USA > Virginia > Richmond", "Earth > North America > USA > Washington, D.C. > Georgetown"]
["North America, Earth", "USA, North America, Earth", "Virginia, USA, North America, Earth", "Washington, D.C., USA, North America, Earth", "Alexandria, Virginia, USA, North America, Earth", "Richmond, Virginia, USA, North America, Earth", "Georgetown, Washington, D.C., USA, North America, Earth"]
如果我想修改或添加单个元素,你会发现它变得很麻烦,因为我有所有这些嵌套调用。而且我必须知道事情的位置,当我真正开始在这里建设时,这将是不切实际的。
我想要的是这样的行为更像一个目录,我有一个指针告诉我我在哪里,然后我可以快速调用对象,无论多深层我都是,因为路径的第一部分已经知道了。我正在试图弄清楚如何做到这一点 - 现在隐约地考虑哈希和查找函数 - 但在我进入它之前,我试图做什么的术语是什么?难道是用纯粹的红宝石而不是学习框架来做这件事吗?解决这类问题的任何概念性的东西或策略?
对不起所有的普遍性,伙计们。我是编码的新手,并不知道如何更简洁地提问。
答案 0 :(得分:0)
add_setting("North America")
也返回设置数组,因此您可以执行以下操作:
earth = Setting.new("Earth");
earth.add_setting("North America").add_setting("USA").add_setting("Virginia")
换句话说,你应该能够做到这一点:
earth = Setting.new("Earth");
north_america = earth.add_setting("North America");
virginia = north_america.add_setting("virginia");