0

Say I have an array of arrays that looks like this:

[[1830, 1], [1859, 1]]

What I want to do is quickly scan the internal arrays to see if any of them contain the number 1830. If it does, I want it to return the entire array that includes the number 1830, aka [1830, 1] from the above example.

I know for a normal array of values, I would just do array.include? 1830, but that doesn't work here, as can be seen here:

@add_lines_num_start
#=> [[1830, 1], [1859, 1]]
@add_lines_num_start.include? 1830
#=> false
@add_lines_num_start.first.include? 1830
#=> true

How do I do that?

2
  • 1
    Suppose the array was [[1830,1], [2, 1830], [3, 1492]] and the number of interest was 1830. Is [[1830,1], [2, 1830]] to be returned? Commented Mar 3, 2017 at 8:18
  • @CarySwoveland Yes, you are correct. Commented Mar 3, 2017 at 8:40

1 Answer 1

6
a = [[1830, 1], [1859, 1]]
a.find { |ar| ar.grep(1830) }
#=> [1830, 1]

References:

edit 1

As @Ilya mentioned in comment, instead of traversing the whole array with grep you could use the method to return the boolean once element that matches the condition is found:

a.find { |ar| ar.include?(1830) }

References:

edit 2 (shamelessly stolen from @Cary's comment under OP)

In case you'll have more than one matching array in your array, you can use Enumerable#find_all:

a = [[1830, 1], [1859, 1], [1893, 1830]]
a.find_all { |ar| ar.include?(1830) }
#=> [[1830, 1], [1893, 1830]]
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect. This is exactly what I am looking for. Thanks!
@marcamillion no probs :)
include? seems to be more readable, moreover: it's more efficient, you don't scan a whole array in this case.
@AlexGolubenko yea, select is an alias of find_all :)

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.