How to search in a two-dimensional array

I am trying to learn how to search in a two-dimensional array; eg:

array = [[1,1], [1,2], [1,3], [2,1], [2,4], [2,5]] 

I want to know how to search in an array arrays of the form [1, y] , and then show that the other y numbers are: [1, 2, 3] .

If someone can help me figure out how to search only with numbers (since many of the examples I found include strings or hashes) and even where I need to search for the necessary resources, this would be helpful.

+5
source share
5 answers

Ruby allows you to peek into an element using parentheses in a block argument. select and map only assign one block argument, but you can look at the element:

 array.select{|(x, y)| x == 1} # => [[1, 1], [1, 2], [1, 3]] array.select{|(x, y)| x == 1}.map{|(x, y)| y} # => [1, 2, 3] 

You can omit the parentheses corresponding to the entire expression between |...| :

 array.select{|x, y| x == 1} # => [[1, 1], [1, 2], [1, 3]] array.select{|x, y| x == 1}.map{|x, y| y} # => [1, 2, 3] 

As an encoding style, the user can mark unused variables as _ :

 array.select{|x, _| x == 1} # => [[1, 1], [1, 2], [1, 3]] array.select{|x, _| x == 1}.map{|_, y| y} # => [1, 2, 3] 
+5
source

You can use Array # select and Array # map :

 array = [[1,1], [1,2], [1,3], [2,1], [2,4], [2,5]] #=> [[1, 1], [1, 2], [1, 3], [2, 1], [2, 4], [2, 5]] array.select { |el| el[0] == 1 } #=> [[1, 1], [1, 2], [1, 3]] array.select { |el| el[0] == 1 }.map {|el| el[1] } #=> [1, 2, 3] 

Additional methods in arrays examine docs .

+6
source

If you select and then match first, you can use the grep function for all this in one function:

 p array.grep ->x{x[0]==1}, &:last #=> [1,2,3] 
+5
source

Another way to do the same is to use Array # map along with Array # compact . This has the advantage of only requiring one block and a trivial operation, which makes it a little easier to understand.

 array.map { |a, b| a if b == 1 } #=> [1, 2, 3, nil, nil, nil] array.map { |a, b| a if b == 1 }.compact #=> [1, 2, 3] 
+1
source

You can use each_with_object :

 array.each_with_object([]) { |(x, y), a| a << y if x == 1 } #=> [1, 2, 3] 
+1
source

All Articles