Retrieving a value from an array in an array

I have an array like this

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

      

I want to pull out the number 3 given that I know I was looking for the value "c".

I tried this but no luck

search_for = 'c'

test = records.select{ |x| x=search_for}

      

I am returning the whole array

+3


source to share


6 answers


You are looking for Array # assoc:



records.assoc(search_for).last

      

+6


source


You can convert the array to a hash and just get a value like this:

search_for = 'c'
test = Hash[records][search_for]   #=> "3"

      



You can also use .key?

to check if a key exists.

+2


source


Not necessarily the cleanest or most idiomatic, but here's a different way:

records.find { |x, y| break(y) if x == "c" }

      

In other words, a predetermined array of pairs x, y

, find

the first pair where x == "c"

and returns the value y

.

+2


source


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

      

+1


source


records.find { |f,_| f == 'c' }.last #=> 3

      

0


source


Can you use Array # include? (value):

Example:

a = [1,2,3,4,5]
a.include?(3)   # => true
a.include?(9)   # => false

      

-1


source







All Articles