3

我有一个嵌套的“主”数组,我希望返回在第二个“匹配”数组中匹配的元素的结果(整个嵌套数组)。我已经能够使用 (main && match) 返回数组所需输出的第一个值,但我可以找到进入嵌套数组的方法。

主要的:

[[111, [100,101,102]], [222, [200,201,202]], [333, [300,301,302]], [444, [400,401,402]], [555, [500,501,502]], [666, [600,601,602]], [777, [700,701,702]]]

匹配:

[222,555,666]

期望的结果:

[[222, [200,201,202]], [555, [500,501,502]], [666, [600,601,602]]]
4

2 回答 2

4

这是一个完美的使用场所Array#assoc

data = [[111, [100,101,102]], [222, [200,201,202]], [333, [300,301,302]], [444, [400,401,402]], [555, [500,501,502]], [666, [600,601,602]], [777, [700,701,702]]]
match = [222,555,666]

p match.map{|i| data.assoc(i)}

#=> [[222, [200, 201, 202]], [555, [500, 501, 502]], [666, [600, 601, 602]]]

文档中,Array#assoc

搜索一个数组,该数组的元素也是数组,使用 obj.== 将 obj 与每个包含数组的第一个元素进行比较。

返回第一个匹配的包含数组(即第一个关联数组),如果没有找到匹配项,则返回 nil。

于 2013-11-15T03:01:55.290 回答
0

使用 aselect匹配每个子数组中的第一个元素:

data = [[111, [100,101,102]], [222, [200,201,202]], [333, [300,301,302]], [444, [400,401,402]], [555, [500,501,502]], [666, [600,601,602]], [777, [700,701,702]]]

match = [222, 555, 666]

results = data.select{|x| match.include?(x[0])}

p results

#=> [[222, [200, 201, 202]], [555, [500, 501, 502]], [666, [600, 601, 602]]]
于 2013-11-15T02:53:29.937 回答