Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.87 KB | None | 0 0
  1. class Tree
  2.     attr_accessor :children, :node_name
  3.    
  4.     def initialize(hash)
  5.         @children = []
  6.         hash.keys.each do |key|
  7.             @node_name = key
  8.             hash[key].keys.each do |keychild|
  9.                 @children << Tree.new(hash[key][keychild])
  10.             end
  11.         end
  12.     end
  13.  
  14.     def visit_all(&block)
  15.         visit &block
  16.         children.each {|c| c.visit_all &block}
  17.     end
  18.    
  19.     def visit(&block)
  20.         block.call self
  21.     end
  22.    
  23.     def to_s
  24.         puts "Node name: " + @node_name + "\n"
  25.         puts "Children:\n"
  26.         children.each do |c|
  27.             puts "\t" + c.to_s
  28.         end
  29.     end
  30. end
  31.  
  32. x = {"grandpa" => { "dad" => {"child 1" => {}, "child 2" => {} }, "uncle" => {"child 3" => {}, "child 4" => {} } } }
  33. y = Tree.new(x)
  34. puts y.to_s
  35.  
  36.  
  37. ./grep.rb:27:in `+': can't convert Array into String (TypeError)
  38.        from ./grep.rb:27:in `to_s'
  39.        from ./grep.rb:26:in `each'
  40.         from ./grep.rb:26:in `to_s'
  41.        from ./grep.rb:34
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement