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
3
  • 4
    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 . Jun 26, 2015 at 20:18
  • thanks, I prefer this to changing it to a hash and @CarySwoveland thanks for the fix! Jun 26, 2015 at 21:06
  • @CarySwoveland I thank you for the fix too. It would be great if you could you leave your comment up with the link.
    – seph
    Jun 26, 2015 at 22:29
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
  • Thanks for the advice, I'm pretty new to ruby, what is .key? Jun 26, 2015 at 20:18
  • @RenaissanceProgrammer: it checks if key is present in the hash.
    – potashin
    Jun 26, 2015 at 20:19
  • Hash.key?(k) is the same as Hash.has_key?(k) and Hash.include?(k). Jun 26, 2015 at 20:21
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
  • 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 Jun 26, 2015 at 21:11
1
test = records.select{ |x| x[0] == search_for }
value = test[0][1]
0
records.find { |f,_| f == 'c' }.last #=> 3
-1

You can use Array#include?(value):

Example:

a = [1,2,3,4,5]
a.include?(3)   # => true
a.include?(9)   # => false
1
  • 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. Jun 26, 2015 at 21:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.