Ruby searching through multidimensional array
Learning the beauty of Ruby code and I was wondering if there is a simple/straightforward to search within a multidimensional array. I have an multi array with 4 indices that contain assorted number. I want to search though each index matching the contents agains another array...seudo codez
multi_array = [ [1,3,7], [3,1,4], [1,3,4], [0,9,2]]
numbers_looking_to_match = [1,5,9]
multi_array.each do | elmt |
elmt.each_with_index do |elmt, idx|
if elmt == numbers_looking_to_match.each { |e| puts "开发者_StackOverflowmatch" }
end
end
I want this to return a new multi array with all non matching characters removed for original multi array.
Using Array#&
for intersection,
multi_array.map {|a| a & numbers_looking_to_match }
multi_array.each { |elem| numbers_looking_to_match.each { |x| elem.delete(x) if elem.include?(x)}
}
To scrub each element of unwanted characters:
require 'set'
multi_array=[ [1,3,7], [3,1,4], [1,3,4], [0,9,2]]
numbers_looking_to_match=Set.new([1,5,9])
scrubbed=multi_array.collect{ |el|
numbers_looking_to_match.intersection(el).to_a
}
puts scrubbed.inspect
# prints [[1], [1], [1], [9]]
精彩评论