Kumo Kumo - 6 months ago 7
Ruby Question

How to search within a two-dimensional array

I'm trying to learn how to search within a two-dimensional array; for example:

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


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

If anyone can help me understand how to search only with numbers (as a lot of the examples I found include strings or hashes) and even where to look for the right resources even, that would be helpful.

Answer

Ruby allows you to look into an element by using parentheses in the block argument. select and map only assign a single block argument, but you can look into 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 that correspond 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 a coding style, it is a custom to 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]
Comments