Friday, June 26, 2015

Searching for a given element in an array of arrays in Ruby

How to pull the number 3 from this list by searching for the value 'c'.

records =
[
 ["a","1"],
 ["b","2"],
 ["c","3"]
]

search_for = 'c'

Solution 1:

test = records.select{ |x| x[0] == search_for }

p test[0][1]

Solution 2:

p records.assoc(search_for).last