tags:

views:

216

answers:

1

I am loading an arbitrary YAML document, and want to walk every node in the tree. I don't know how nested the tree is beforehand, so I can't just use a simple each statement to walk all the nodes.

Here is how I'm loading the document:

tree = File.open( "#{RAILS_ROOT}/config/locales/es.yml" ){ |yf| YAML::load (yf)}
+3  A: 
def traverse(obj, &blk)
  case obj
  when Hash
    # Forget keys because I don't know what to do with them
    obj.each {|k,v| traverse(v, &blk) }
  when Array
    obj.each {|v| traverse(v, &blk) }
  else
    blk.call(obj)
  end
end

traverse( YAML.load_file(filename) ) do |node|
  puts node
end

Edit:

Note that this only yields the leaf nodes. The question wasn't very clear as to what was wanted exactly.

sepp2k
sepp2k: the leaf nodes is exactly what I wanted, this is perfect!
Summit Guy