使用深度键将哈希树转换为哈希数组

时间:2015-04-24 09:55:50

标签: ruby arrays hashmap

给出这样的哈希树:

flat_array = [
  { value: 1, text: "foo", depth: 0 },
  { value: 2, text: "bar", depth: 0 },
  { value: 3, text: "baz", depth: 1 },
  { value: 4, text: "quz", depth: 2 },
  { value: 5, text: "norf", depth: 0 }
]

我想要一种优雅的方法来创建一个哈希的平面数组,并保留顺序,并将深度添加到每个哈希作为键,例如:

{{1}}

组成哈希树的每个对象都比上面的例子中的更复杂,但是我的数组中需要的是ID和标题 - 但请注意,键已经改变了。 / p>

由于

1 个答案:

答案 0 :(得分:2)

我已将hash_tree更改为打开结构,因此我可以使用它,但我认为我得到的是你的目标:

require 'ostruct'

hash_tree = {
  OpenStruct.new(id: 1, title: "foo") => {},
  OpenStruct.new(id: 2, title: "bar") => {
    OpenStruct.new(id: 3, title: "baz") => {
      OpenStruct.new(id: 4, title: "qux") => {}
    }
  },
  OpenStruct.new(id: 5, title: "norf") => {}
}


def flat_tree(hash, depth = 0)
  hash.each_with_object([]) do |(obj, v), results|
    results << { value: obj.id, text: obj.title, depth: depth }
    results << flat_tree(v, depth + 1) if v.is_a?(Hash) && !v.empty?
  end
end

puts flat_tree(hash_tree)

输出:

{:value=>1, :text=>"foo", :depth=>0}
{:value=>2, :text=>"bar", :depth=>0}
{:value=>3, :text=>"baz", :depth=>1}
{:value=>4, :text=>"qux", :depth=>2}
{:value=>5, :text=>"norf", :depth=>0}