3

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 "match" }
  end 
end

I want this to return a new multi array with all non matching characters removed for original multi array.

2
  • Are you trying to remove numbers from within each element of multi_array? Or throw out an element of multi_array if it doesn't contain an exact match for numbers_looking_to_match? Also, do you care about order of numbers in each element? Commented Oct 1, 2011 at 20:09
  • What I am trying to do is remove number not matching the number_looking_to_match...so if we look at the multi array and numbers_looking_to_match arrays the return of the function should provide me with a result == [[1],[1],[1],[9] but Not limited to one result. Commented Oct 6, 2011 at 19:32

3 Answers 3

6

Using Array#& for intersection,

multi_array.map {|a| a & numbers_looking_to_match }
Sign up to request clarification or add additional context in comments.

1 Comment

what if the array has mixed types? the first element in my array is a Fixnum and the rest are Arrays or Strings
1

multi_array.each { |elem| numbers_looking_to_match.each { |x| elem.delete(x) if elem.include?(x)} }

Comments

1

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.