gpt4 book ai didi

ruby - 在 Ruby 中返回匹配的嵌套数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:14 25 4
gpt4 key购买 nike

我有一个嵌套的“主”数组,我希望返回在第二个“匹配”数组中匹配的元素的结果(整个嵌套数组)。我已经能够使用 (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]]]

最佳答案

这是使用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]]]

来自docs , 数组#assoc

Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==.

Returns the first contained array that matches (that is, the first associated array), or nil if no match is found.

关于ruby - 在 Ruby 中返回匹配的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19992626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com