edubkendo
7/30/2013 - 11:47 PM

gistfile1.md

I have an object node. Each node can have an array of child_nodes:


node 

#=> (RootNode, (BlockNode, (NewlineNode, (DefnNode:foo, (MethodNameNode:foo), (ArgsNode, (ListNode, (ArgumentNode:bar))), (NewlineNode, (LocalVarNode:bar)))), (NewlineNode, (FCallNode:foo, (ArrayNode, (StrNode)))), (NewlineNode, (DefnNode:quux, (MethodNameNode:quux), (ArgsNode), (NewlineNode, (FCallNode:puts, (ArrayNode, (FCallNode:foo, (ArrayNode, (StrNode))))))))))

node.child_nodes

#=> [(BlockNode, (NewlineNode, (DefnNode:foo, (MethodNameNode:foo), (ArgsNode, (ListNode, (ArgumentNode:bar))), (NewlineNode, (LocalVarNode:bar)))), (NewlineNode, (FCallNode:foo, (ArrayNode, (StrNode)))), (NewlineNode, (DefnNode:quux, (MethodNameNode:quux), (ArgsNode), (NewlineNode, (FCallNode:puts, (ArrayNode, (FCallNode:foo, (ArrayNode, (StrNode)))))))))]

I want to write a method that, given a node will return an array that contains the child_nodes and those nodes child_nodes, all the way down recursively. The child_nodes method will return [] if the node has no children.

I can get the value I want like this:

@children = []

def recursive_children(node)

  node.child_nodes.each do |child|
    @children << child
    recursive_children(child)
  end

end

recursive_children(node)
puts @children

But this feels ungainly to me, and I want the method itself to return that value, but I'm just not quite getting it.