RenaissanceProgrammer
RenaissanceProgrammer

Reputation: 484

Extract value out of array within an array

I have an array like this

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

I want to pull the number 3, given that I known I am searching for the value of "c".

I've tried this but no luck

search_for = 'c'

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

I get back the whole array

Upvotes: 3

Views: 595

Answers (6)

seph
seph

Reputation: 6076

You're looking for Array#assoc:

records.assoc(search_for).last

Upvotes: 6

Alexandre Abreu
Alexandre Abreu

Reputation: 1417

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

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

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

Upvotes: 0

Matt Brictson
Matt Brictson

Reputation: 11082

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

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

In other words, given an array of pairs x, y, find the first pair where x == "c" and return the value of y.

Upvotes: 2

Wanderley
Wanderley

Reputation: 399

You can use Array#include?(value):

Example:

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

Upvotes: -1

potashin
potashin

Reputation: 44581

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

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

You may also consider to use .key? to check if key is present.

Upvotes: 2

Related Questions