4

I have this nested array:

array = [
      ["A", "X"],
      ["B", "Y"],
      ["C", "Z"]
]

Is there a function that returns "B" when I provide "Y" and "C" when I provide "Z"?

1
  • 2
    Picky-picky point: it would better to change 'and "C"' to 'and return "C"'. Initially I thought you were providing "Y" and "C" and wanted "B", which seemed odd and made the sentence undecipherable. Of course, I may be the only person in the room who read it that way. Commented Jul 25, 2016 at 15:15

4 Answers 4

13

rassoc might be what you need.

array.rassoc("Y") would return ["B", "Y"] and you can use first to get only the "B".

Sign up to request clarification or add additional context in comments.

Comments

3

You can use find method.

array = [
  ["A", "X"],
  ["B", "Y"],
  ["C", "Z"]
]


str = "Y"
arr = array.find{|a| a[1] == str}
puts arr[0] if arr
# => B

Comments

3

Or, you can convert it to a Hash, if you need to do many lookups and the array is biggish:

hash = array.map(&:reverse).to_h
hash["Y"]
# => "B"

Comments

1

There is no such internal function out of the box, but one might easily create one:

▶ λ = ->(input) { array.detect { |e| e.last == input }.first rescue nil }
#⇒ #<Proc:0x0000000437f150@(pry):10 (lambda)>
▶ λ.('X')
#⇒ "A"
▶ λ.('Y')
#⇒ "B"
▶ λ.('QQQ')
#⇒ nil

Comments

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.