3

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

6 Answers 6

6

You're looking for Array#assoc:

records.assoc(search_for).last
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, but you forgot .last. I suggest your write records.assoc('c').last => "3". I'll delete this comment when you've seen it (no reply req'd). Also, the link for the method is ruby-doc.org/core-2.2.0/Array.html#method-i-assoc .
thanks, I prefer this to changing it to a hash and @CarySwoveland thanks for the fix!
@CarySwoveland I thank you for the fix too. It would be great if you could you leave your comment up with the link.
2

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.

3 Comments

Thanks for the advice, I'm pretty new to ruby, what is .key?
@RenaissanceProgrammer: it checks if key is present in the hash.
Hash.key?(k) is the same as Hash.has_key?(k) and Hash.include?(k).
2

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.

1 Comment

awesome I really like this answer because it's intuitive enough to understand what to do with the array has more than 2 values, and if the value i'm trying to extract is not .last like in seph's* answer
1
test = records.select{ |x| x[0] == search_for }
value = test[0][1]

Comments

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

Comments

-1

You can use Array#include?(value):

Example:

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

1 Comment

Sorry but this isn't what my question was asking. a) this doesn't return the value, b) I don't know the value to begin with, only the associated key, hence "given i know I'm searching for 'c'", so I can't check to see if it's included if I don't know it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.