Alexander Donets Alexander Donets - 8 days ago 6
Ruby Question

Ruby How to access a "key" of a two-dimensional array?

I have an array like that which I use in f.select when updating a user profile

SEX = [["Male", 'M'],
["Female", 'F']]


I'd use a hash but I couldn't make it work at all with a select thing. So I have a select dropdown with values "Male" and "Female" and it assigns a value of "M" or "F" to user variable :sex. Now, when showing the profile I need to output sex as a "key" here (Male or Female, not M/F). How can I access these "key" values besides making huge get_sex and other getters for bigger arrays methods which won't be DRY at all? What can I do here?

Answer

You need to use rassoc method https://ruby-doc.org/core-2.2.0/Array.html#method-i-rassoc

sex = [["Male", "M"], ["Female", "F"]]
sex.rassoc("M")
 => ["Male", "M"] 
sex.rassoc("M").first
 => "Male" 
Comments