tyronegcarter tyronegcarter - 6 months ago 12
Ruby Question

How to check if specific value is present in a hash?

I'm using Rails and I have a hash object. I want to search the hash for a specific value. I don't know the keys associated with that value.

How do I check if a specific value is present in a hash? Also, how do I find the key associated with that specific value?

rkb rkb
Answer

Hash includes Enumerable, so you can use the many methods on that module to traverse the hash. It also has this handy method:

hash.has_value?(value_you_seek)

To find the key associated with that value:

hash.key(value_you_seek)

This API documentation for Ruby (1.9.2) should be helpful.