Ruby 如何递归搜索自引用子主题?

Ruby 如何递归搜索自引用子主题?,ruby,recursion,Ruby,Recursion,如果我有一个自引用的主题类,并且我想递归地循环遍历我的所有子主题,那么Ruby有什么好方法可以做到这一点: @category.topics.all(:parent_id => topic.id).each do |subtopic| subtopic.delete_tags @category.topics.all(:parent_id => subtopic.id).each do |subsubtopic| subsubtopic.delete_tags

如果我有一个自引用的主题类,并且我想递归地循环遍历我的所有子主题,那么Ruby有什么好方法可以做到这一点:

@category.topics.all(:parent_id => topic.id).each do |subtopic|
    subtopic.delete_tags
    @category.topics.all(:parent_id => subtopic.id).each do |subsubtopic|
    subsubtopic.delete_tags
        @category.topics.all(:parent_id => subsubtopic.id).each do |subsubsubtopic|
        subsubtopic.delete_tags
            @category.topics.all(:parent_id => subsubsubtopic.id).each do |subsubsubsubtopic|
            subsubsubtopic.delete_tags
            end
        end
    end
end
像这样的

class Topic
  def delete_subtopic_tags
    all(:parent_id => self.id).each do |subtopic|
      subtopic.delete_subtopic_tags
      subtopic.delete_tags
    end
  end
end

这是ActiveRecord模型类吗?如果是这样,您应该能够使用类似以下代码的方式通过子对象干净地递归:

class Topic
  has_many :topics
  belongs_to :parent, :classname => "Topic", :foreign_key => 'parent_id'

  # ...other model class logic...
  def delete_tags_recursive
    delete_tags
    topics.each {|subtopic| subtopic.delete_tags_recursive }
  end
end

这还有一个额外的好处,就是允许您使用由
创建的
主题
父类
方法,这些方法有许多
属于
装饰程序,以便轻松地遍历主题树。

我不知道Ruby,但是如果您手头有哈希表和链表实现,我会这样做(在Java伪代码中):


这里的要点是保留hashtable列表,这样您就可以轻松地确保一个主题不会访问两次为每个主题执行任何您需要执行的操作。

这会进入无限循环吗?如果数据库中存在任何主题的
parent\u id
等于它们自己的
id
,则是的,它会。@jprete:只有当某个主题本身是子主题时,它才会是无限的。但这似乎本身就是一个错误。否则,递归n将在到达没有子主题的主题时结束。但它似乎应该是
:parent\u id=>self.id
Topic currentTopic = topic;
list.add(currentTopic);
hashtable.add(currentTopic);
while (list.empty() == false) {
    for (Topic t : currentTopic.getSubtopics()) {
        if (hashtable.contains(t) == false) {
            list.add(t);
            hashtable.add(t);
        }
    }
    visit(currentTopic);
    list.remove(currentTopic);
    currentTopic = list.getFirst();
}