Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a nested "main" array and I am looking to return the results (the entire nested array) for elements matched in a second "match" array. I have been able to return the first value of the arrays desired output using (main && match) but I can find a way into the nested array.

Main:

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

Desired Results:

[[222, [200,201,202]], [555, [500,501,502]], [666, [600,601,602]]]
share|improve this question

2 Answers 2

up vote 4 down vote accepted

This is a perfect place to use 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]]]

From the docs, Array#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.

share|improve this answer

Use a select to match on the first element in each of the sub-arrays:

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]]]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.