0

i have an array of hashes, eg

array = [
{ id: 1, name: 'root' parent: null},
{ id: 2, name: 'first' parent: 1},
{ id: 5, name: 'first step' parent: 2},
{ id: 6, name: 'second step' parent: 2},

{ id: 3, name: 'second' parent: 1},
{ id: 7, name: 'first step' parent: 3},

{ id: 4, name: 'third' parent: 1},
{ id: 2, name: 'first' parent: 1},

]

and i need to build something like that

hash = {
  { 
  id: 1,
  name: 'root',
  parent: null,
  childrens: [
    { id: 2,
    name: 'first',
    parent: 1,
    childrens: [
      {
        id: 5,
        name: 'first step',
        parent: 2
      },
      {
        id: 6,
        name: 'second step',
        parent: 2
      },
  ]},
  ...
}

I am newbie at ruby and doesnot understand how to do this. Probably i need to use recursive functions? Or not?

5
  • 1
    Thats not a valid Hash. And in ruby it is nil, not null Commented Jun 4, 2014 at 11:33
  • i konw this, it is just an example Commented Jun 4, 2014 at 11:40
  • Yes you will have to use a recursive function. ¿Is this something related to rails? Commented Jun 4, 2014 at 11:44
  • yes. In fact, i have awesome_nested_set and i need to make such thing with this gem Commented Jun 4, 2014 at 11:46
  • Never used this gem, but this other one worked perfect for me: github.com/stefankroes/ancestry ¿Is it an option? Commented Jun 4, 2014 at 11:51

1 Answer 1

1
# Put all your nodes into a Hash keyed by id  This assumes your objects are already Hashes
object_hash = nodes.index_by {|node| node[:id]}
object_hash[0] = {:root => true}

# loop through each node, assigning them to their parents
object_hash.each_value {|node|
  next if node[:root]
  children = object_hash[node[:parent_id]][:children] ||= []
  children << node
}

#then your should have the structure you want and you can ignore 'object_hash' variable
tree = object_hash[0]

From the answer:

Algorithm for parsing a flat tree into a non-flat tree

Sign up to request clarification or add additional context in comments.

1 Comment

yes, its great, but we use awesome_nested_set and i cant use this gem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.