简体   繁体   中英

How do I check to see if an array of arrays has a value within the inner arrays?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM