6

I have array of arrays, which looks like this:

a = [['1','1500','SomeName','SomeSurname'],
['2','1500','SomeName2','SomeSurname2'],
['3','1500','SomeName3','SomeSurname3'],
['4','1501','SomeName','SomeSurname'],
...]

I can get sub-array of this array with all rows containing '1500' value by .each function and simple if, but if a.length is large, it's taking too much time! How can I get all rows from a with certain a[1] value, without iterating over a?

0

3 Answers 3

10

Enumerable#find_all is what you are looking for:

a.find_all { |el| el[1] == '1500' } # a.select will do the same
Sign up to request clarification or add additional context in comments.

Comments

7

You have a few options, you could use a find:

a.find { |l| l[1] == '5' }

This would find the array that matches the first 5

You need to use find_all to find all:

a.find_all { |l| l[1] == '5' }

2 Comments

But will it find all matches, or only the first one?
Andrey has nailed it, I missed that you wanted all
1

Use select to get all matching elements:

a.select { |e| e[1] == '1500' }

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.