Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 770
Kumo Avatar asked Apr 20 '15 10:04

Kumo


2 Answers

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]
like image 121
sawa Avatar answered Nov 15 '22 08:11

sawa


You can use Array#select and Array#map methods:

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]

For more methods on arrays explore docs.

like image 36
Andrey Deineko Avatar answered Nov 15 '22 07:11

Andrey Deineko