How do I move all nodes in a YAML tree in Ruby?

I load an arbitrary YAML document and want to walk every node in the tree. I don’t know how to nest the tree in advance, so I can’t just use a simple operator to walk through all the nodes.

This is how I upload a document:

tree = File.open( "#{RAILS_ROOT}/config/locales/es.yml" ){ |yf| YAML::load (yf)}
+3
source share
2 answers
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 gives leaf nodes. The question was not very clear about what was needed for sure.

+12
source

YAML node, . node, , , YAML. @sepp2k:

require 'yaml'

def traverse(obj,parent, &blk)
 case obj
 when Hash
   obj.each do |k,v| 
     blk.call(k,parent)
     # Pass hash key as parent
     traverse(v,k, &blk) 
   end
 when Array
   obj.each {|v| traverse(v, parent, &blk) }
 else
   blk.call(obj,parent)
 end
end


# Example, creating a database tree structure, from your YAML file.
# Passing nil to root node(s) as parent

tree_str =<<EOF
  Regions:
    - Asia
    - Europe
    - Americas
  Other:
    - Foo:
      - bar
      - buz
EOF

traverse( YAML.load(tree_str), nil ) do |node,parent|
  puts "Creating node '#{node}' with parent '#{ parent || 'nil' }'"
end
+4

Source: https://habr.com/ru/post/1715572/


All Articles