Ruby: Find a hash key given it's value

Updated . Posted . Visible to the public.

To find a hash key by it's value, i.e. reverse lookup, one can use Hash#key Show archive.org snapshot . It's available in Ruby 1.9+.

Hash#key(value) → key
# => Returns the key of the first occurrence of a given value.
     If the value is not found, returns nil.

hash = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
hash.key(200)   #=> "b"
hash.key(300)   #=> "c"
hash.key(999)   #=> nil

Last edit
Deleted user #3651
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2015-02-13 14:49)