Dorian Dorian - 5 months ago 32
Ruby Question

Ruby on Rails get key by value from two dimensional array

I have a two dimensional array that looks like this:

TITLETYPE = [['Prof.', '4'],
['Dr.', '3'],
['Mrs.', '2'],
['Ms.', '1'],
['Mr.', '0']]

I need to get the key for value 1 for example (which should be 'Ms.')
How should I go about doing that?

rid rid
Answer{ |x| x[1] == '1' }.first.first

How this works

You can use Array's select method to find the row you're looking for. Your rows ar arrays with two elements each (element 0 and element 1), so you need to look for the row in which the second element (element 1) is equal to the value you're looking for (which is the string "1"):{ |x| x[1] == "1" }

This will return an array with only one row:

[["Ms.", "1"]]

To get the first and only value from that array, use Array's first method, which will return:

["Ms.", "1"]

Then, from that, obtain the first value from the two values with first again: