Read more

Ruby: Find a hash key given it's value

Avatar
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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more
Posted by Thomas Klemm to makandra dev (2015-02-13 15:49)