Read more

Ruby: Find a hash key given it's value

Thomas Klemm
February 13, 2015Software engineer

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot
Posted by Thomas Klemm to makandra dev (2015-02-13 15:49)