从多维数组中获取特定信息

时间:2017-02-20 01:42:24

标签: ruby-on-rails arrays ruby ruby-on-rails-3

假设我有这种格式的数组:

arr = [{
         "id":"11",
         "children":[
                      { "id":"9"},
                      { "id":"5", "children":[ {"id":"4"} ] }
                    ]
       },
       {
         "id":"10",
         "children":[{ "id":"7"} ]
       }
      ]

现在我想在这个数组中获得所有明显的ID

11,9,5,4,10,7

为此我会使用类似于这个的递归代码:

ids = []

def find_ids arr
 arr.each do |entry|
   ids << entry["id"] if entry["id"]
   find_ids(entry["children"]) if entry["children"]
 end 
end

你会做些什么来获取ID?

您是否知道一个非常简短的版本?

由于

3 个答案:

答案 0 :(得分:1)

def grab_ids(arr)
  arr.each_with_object([]) do |h,a|
    h.each do |k,v|
      case v
      when Array
        a.concat(grab_ids(v))
      else
        a << v if k == :id
      end
    end
  end
end

grab_ids arr
  #=> ["11", "9", "5", "4", "10", "7"]

答案 1 :(得分:1)

其他方式是使用lambda:

def get_ids(arr)
  p = ->(a, exp) do
    a.each do |hsh|
      exp << hsh["id"]
      p.(hsh["children"], exp) if Array === hsh["children"]
    end
    exp
  end
  p.(arr, [])
end

get_ids(arr)
# => ["11", "9", "5", "4", "10", "7"]

答案 2 :(得分:0)

或者如果你想使用更短的版本:

def get_ids(arr)
  p =->(hsh) { Array === hsh["children"] ? ([hsh["id"]] + hsh["children"].map(&p)) : hsh["id"] }

  arr.map(&p).flatten
end

get_ids(arr)
# => ["11", "9", "5", "4", "10", "7"]
相关问题