递归DFS Ruby方法

时间:2010-12-06 16:53:38

标签: ruby recursion yaml traversal depth-first-search

我有一个YAML file of groups我希望进入名为群组的MongoDB集合,其中包含{"name" => "golf", "parent" => "sports"}等文档(顶级群组,如体育,只有{"name" => "sports"}没有{ {1}}。)

我们正在尝试traverse the nested hash,但我不确定它是否正常工作。我更喜欢使用递归方法而不是lambda proc。我们应该改变什么来使其发挥作用?

谢谢!

马特

2 个答案:

答案 0 :(得分:2)

这是工作代码:

require 'mongo'
require 'yaml'

conn = Mongo::Connection.new
db = conn.db("acani")
interests = db.collection("interests")
@@interest_id = 0
interests_hash = YAML::load_file('interests.yml')

def interests.insert_interest(interest, parent=nil)
  interest_id = @@interest_id.to_s(36)
  if interest.is_a? String # base case
    insert({:_id => interest_id, :n => interest, :p => parent})
    @@interest_id += 1
  else # it's a hash
    interest = interest.first # get key-value pair in hash
    interest_name = interest[0]
    insert({:_id => interest_id, :n => interest_name, :p => parent})
    @@interest_id += 1
    interest[1].each do |i|
      insert_interest(i, interest_name)
    end
  end
end

interests.insert_interest interests_hash

查看Interests YAML 查看acani source

答案 1 :(得分:0)

您的问题是如何转换此代码:

insert_enumerable = lambda {|obj, collection|
   # obj = {:value => obj} if !obj.kind_of? Enumerable
   if(obj.kind_of? Array or obj.kind_of? Hash)
      obj.each do |k, v|
        v = (v.nil?) ? k : v
        insert_enumerable.call({:value => v, :parent => obj}, collection)
      end
   else
      obj = {:value => obj}
   end
   # collection.insert({name => obj[:value], :parent => obj[:parent]})
   pp({name => obj[:value], :parent => obj[:parent]})
}

...使用方法而不是lambda?如果是,那么:

def insert_enumerable( obj, collection )
   # obj = {:value => obj} if !obj.kind_of? Enumerable
   if(obj.kind_of? Array or obj.kind_of? Hash)
      obj.each do |k, v|
        v = (v.nil?) ? k : v
        insert_enumerable({:value => v, :parent => obj}, collection)
      end
   else
      obj = {:value => obj}
   end
   # collection.insert({name => obj[:value], :parent => obj[:parent]})
   pp({name => obj[:value], :parent => obj[:parent]})
end

如果那不是您所要求的,请帮助澄清。