Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.66 KB | None | 0 0
  1. class Tree
  2.     attr_accessor :children, :node_name
  3.    
  4.     def initialize(hash)
  5.         @children = []
  6.         hash.keys.each { |k|
  7.             @node_name = k
  8.             hash[k].keys.each { |ck|
  9.                 @children << Tree.new(hash[k][ck])
  10.             }
  11.         }
  12.     end
  13.    
  14.     # def initialize(name, hash)
  15.         # @children = []
  16.         # @node_name = name
  17.         # hash[name].keys.each { |k|
  18.             # @children << Tree.new(k, hash[name][k])
  19.         # }
  20.     # end
  21.  
  22.     def visit_all(&block)
  23.         visit &block
  24.         children.each {|c| c.visit_all &block}
  25.     end
  26.    
  27.     def visit(&block)
  28.         block.call self
  29.     end
  30. end
  31.  
  32. x = {"grandpa" => { "dad" => {"child 1" => {}, "child 2" => {} }, "uncle" => {"child 3" => {}, "child 4" => {} } } }
  33. y = Tree.new(x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement