views:

42

answers:

2

In Ruby, how can I traverse an arbitrary document retrieved from a collection using something like mongomapper? Let's say the document looks something like this:

mydocs = 
[{"title":"my title",
 "description":"hello world",
 "comments":[{"user":"me","text":"this"},{"user":"him","text":"that"}]
 },
 {.....}
]
+1  A: 
def traverse(obj, level=0, name='root')
  s =  "  "*level + name.to_s + ": "
  if obj.is_a?(Array)
    puts s
    obj.each_with_index{ |child,idx| traverse(child,level+1,idx) }
  elsif obj.is_a?(Hash)
    puts s
    obj.each{ |k,v| traverse(v,level+1,k) }
  else
    puts s + obj.inspect
  end
end

traverse mydocs
zed_0xff
I mean to visit each object. It is arbitrary, however, so I'm a little confused at how to proceed for nested elements.
Dex
I updated my answer
zed_0xff
+1  A: 

After fetch a document from MongoMapper/Mongoid or even mongo-ruby-driver, it's like you generate an Hash.

So you can tranverse it like all hash in Ruby World

shingara