Functional and recursive approach:
require 'facets' def create_tree(pairs, root) relationships = pairs.map_by { |parent, child| [parent, child] } get_children = proc do |parent| (relationships[parent] || []).mash do |child| [child, get_children.call(child)] end end get_children.call(root) end pairs = [[1, 2], [1, 6], [1, 9], [2, 3], [3, 10], [4, 7]] p create_tree(pairs, 1)
[edit] Without edges (and now you will understand why I use it!):
def create_tree(pairs, root) relationships = Hash[pairs.group_by { |p, c| p }.map { |p, ary| [p, ary.map { |p, c| c }] }] get_children = proc do |parent| Hash[(relationships[parent] || []).map do |child| [child, get_children.call(child)] end] end get_children.call(root) end
source share