small medium large xlarge

Generic-user-small
29 Nov 2016, 14:33
Jeffrey Knight (1 post)

From Day 2 Self-Study, page 31 - Is there a more “Ruby-esque” way to word this syntax?

class Tree
    attr :hashes

    def initialize(hashes)
        @hashes = hashes
    end 

    def visit()
        visit_all hashes
    end 
   
    private
    def visit_all(node, depth = 1)
        node.each {|c| 
            if c.is_a?(String)
                padding = Array.new(depth, "-").join('')
                puts padding + c 
            else
                visit_all c, (depth + 1)
            end 
        }   
    end 

end

hash = {'grandpa' => {'dad' => {'child 1' => {}, 'child 2' => {} }, 'uncle' => {'child 3' => {}, 'child 4' => {} }}} 

tree = Tree.new(hash)
tree.visit()

Outputs:

-grandpa
---dad
-----child 1
-----child 2
---uncle
-----child 3
-----child 4
You must be logged in to comment