Reputation: 484
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
Reputation: 1417
test = records.select{ |x| x[0] == search_for }
value = test[0][1]
Upvotes: 1
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
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
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