创建嵌套哈希RUBY

创建嵌套哈希RUBY,ruby,Ruby,我有一个哈希数组,例如 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}

我有一个哈希数组,例如

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},
]

我需要建造这样的东西

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
      },
  ]},
  ...
}
我是ruby的新手,不知道怎么做。 可能我需要使用递归函数?是否?

#将所有节点放入由id键控的散列中。这假设您的对象已经是散列
# 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]
object_hash=nodes.index_by{| node | node[:id]} 对象\u哈希[0]={:root=>true} #循环遍历每个节点,将它们分配给其父节点 object_hash.each_值{|节点| 下一个if节点[:根] children=object_hash[node[:parent_id][:children]| |=[]
儿童不是有效的散列。在ruby中,它是
nil
,而不是null我知道这一点,这只是一个例子是的,你必须使用递归函数。这与rails有关吗?是的。事实上,我有很棒的嵌套集,我需要用这个gem制作这样的东西。我从未使用过这个gem,但另一个对我来说很好:是吗一个选择?是的,很好,但是我们使用了很棒的套装,我不能用这个宝石