Функциональный и рекурсивный подход:
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)
#=> {6=>{}, 2=>{3=>{10=>{}}}, 9=>{}}
[править] Без фасетов (и теперь вы поймете, почему я его использую!):
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