How to check if element exists in hash or not in Ruby with examples

Array contains key and value pairs, Sometimes we want to check if a given key exists, resulting in a boolean values checks against conditional statements such as if-else.

Check Key exists in a hash or not

There are multiple ways we can check key exists in a hash.

  • use the hash key? method

key? method checks hash for key exists or not, return true or false.

Here is an example program

emp =  { id: 1, name:"john" }

puts emp.key?(:id) #=> true
puts emp.key?(:id1) #=> false
  • using member? method

Hash member? checks for key exists or not and return true or false.

If the key exists, return true, else return false.

Here is an example program

emp =  { id: 1, name:"john" }

puts emp.member?(:id) #=> true
puts emp.member?(:id1) #=> false
  • use has_key? method

has_key? method checks for keys exist or not and returns true or false. Here is an example program. This was introduced in Rail 5.

emp =  { id: 1, name:"john" }

puts emp.has_key?(:id) #=> true
puts emp.has_key?(:id1) #=> false

Conclusion

To summarize, There are multiple ways to check key exist in hash object with examples.