来自多维数组的Ruby Extract数组

时间:2017-02-17 18:03:52

标签: ruby-on-rails arrays ruby

我有一个多维数组,如:

arr1 = [["text1", 1], ["text2", 2], ["    text3", 3], ["    text4", 4], ["text5", 5], ["text6", 6], ["text7", 7]]

和另一个

arr2 = [2,3,6]

如果它包含arr2的元素,我想提取整个数组。所以,结果应该是:

arr = [["text2", 2], ["    text3", 3], ["text6", 6]].

我尝试了很多方法,但无法得到结果。尝试如:

arr1.each { |elem| arr2.each { |x| elem.delete_if{ |u| elem.include?(x) } } }

arr2.map { |x| arr1.map{|key, val| val.include?(x) }}

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:3)

试试这个

arr1.select { |a| a.any? { |item| arr2.include? item } }
 => [["text2", 2], ["    text3", 3], ["text6", 6]] 

答案 1 :(得分:1)

arr1.select { |(_, d)| arr2.include? d }

答案 2 :(得分:0)

arr1.inject([]) { |result, array| (array & arr2).any? ? result << array : result }
#=> [["text2", 2], ["&nbsp;&nbsp;&nbsp;&nbsp;text3", 3], ["text6", 6]]

从目标角度来看,稍微短一些,更正确:

arr1.select { |array| (array & arr2).any? }