Reputation: 33755
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?
Upvotes: 0
Views: 47
Reputation: 52357
a = [[1830, 1], [1859, 1]]
a.find { |ar| ar.grep(1830) }
#=> [1830, 1]
References:
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:
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]]
Upvotes: 6