Ruby on rails 从多维数组中获取特定信息
假设我有一个如下格式的数组:Ruby on rails 从多维数组中获取特定信息,ruby-on-rails,arrays,ruby,ruby-on-rails-3,Ruby On Rails,Arrays,Ruby,Ruby On Rails 3,假设我有一个如下格式的数组: arr = [{ "id":"11", "children":[ { "id":"9"}, { "id":"5", "children":[ {"id":"4"} ] } ] }, { "id":"10", "children":[{ "id
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
ids=[]
def find_id arr
到达每个do |入口|
ids<代码>def抓取_ids(arr)
每一个带有对象([])的对象都有一个|
h、 每个都有| k,v|
案例五
当数组
a、 concat(抓斗ID(v))
其他的
a[“11”、“9”、“5”、“4”、“10”、“7”]
def抓斗ID(arr)
每一个带有对象([])的对象都有一个|
h、 每个都有| k,v|
案例五
当数组
a、 concat(抓斗ID(v))
其他的
a[“11”、“9”、“5”、“4”、“10”、“7”]
另一种方法是使用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"]
def get_id(arr)
p=->(a,exp)do
a、 每个都有| hsh|
exp[“11”、“9”、“5”、“4”、“10”、“7”]
另一种方法是使用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"]
def get_id(arr)
p=->(a,exp)do
a、 每个都有| hsh|
exp[“11”、“9”、“5”、“4”、“10”、“7”]
或者如果您想使用较短的版本:
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"]
或者,如果您想使用较短的版本:
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"]
约翰,我相信我做的编辑对你没问题。我重新格式化了输入数组以显示其结构,同时也避免了读者需要水平滚动才能看到它。我还向它附加了一个变量(
arr
),以便读者无需定义变量即可引用该变量。将您想要的结果显示为Ruby对象会很有帮助(无论何时给出示例)。在这里,你可能会要求[11,9,5,4,10,7]
。除非你想把字符串转换成整数,否则就用[11,9,5,4,10,7]
。我在发布答案之前没有仔细阅读你的问题,这与您的建议几乎相同,只是我允许使用键-值对,其中键不是:id
,值不是数组。注意{id:1}}=>{:id=>1}
,也就是说,引号是多余的(并且仅当字符串包含空格({ab:1}}}
)时才需要引号。因此,{id:1}[“id”]\=>nil
。您需要{id:1}[:id]#=>1
。当arr
具有交替嵌套数组和散列(到任何级别)时,您确实需要递归来获得所需的数组。如果arr
的结构如示例中所示是固定的,只允许非数组值变化,那么,是的,有一种更简单的方法。John,我相信我所做的编辑对您来说是合适的。我重新格式化了输入数组以显示其结构,也避免读者需要水平滚动才能看到它。我还附加了一个变量to它(arr
)以便读者无需定义即可引用变量。将所需结果显示为Ruby对象(无论何时给出示例)将很有帮助。在这里,您可以要求[11,9,5,4,10,7]
。使[“11”,“9”,“5”,“4”,“10”,“7”]
,除非您希望字符串转换为整数。在发布我的答案之前,我没有仔细阅读您的问题,这与您的建议几乎相同,只是我允许使用键-值对,其中键不是:id
,值不是数组。注意{“id”:1}{id=>1}
,也就是说,引号是多余的(并且仅当字符串包含空格({“ab”:1}}=>{:“ab”=>1}
),因此,{“id”:1}[“id”]\=>nil
。您需要{id:1}[:id]#=>1
。当arr
具有交替嵌套数组和散列(任何级别)时,确实需要递归来获得所需数组。如果arr
的结构如示例中所示是固定的,只允许非数组值变化,那么,是的,有一种更简单的方法。