Two way lookup of id vs name ruby

Viewed 172

I have a hash in which id is the key and name is the value. Both id and value are unique.

Something like this:

h[1] = "ABC"
h[3] = "DEF"

So, if I am given the key of 1, I can easily return a value "ABC".

I need to do a reverse lookup as well, which means if I am given a value of "DEF", I should return 3.

Also, instead of a single value or single key to do the lookup,
I may be provided with an array of values or array of keys instead.

Should I implement two hashes, one for each, or is there any other way in ruby or rails to achieve that?

Edit: This question is not related to finding a key by its value in a hash. It is related to doing a two way lookup not in O(n) time with a better method other than creating two separate hashes.

2 Answers

You can get your key this way: hash.key(value) => key Hash#key

h = { 1 => 'ABC', 3 => 'DEF' }
puts h.key('DEF')
#=> 3

You can use Hash#invert as below,

reversed_h = h.invert

reversed_h['DEF']
# => 3
Related