{

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to install and uninstall gem in Ruby Programming| Ruby on Rails by Example

How to do sum of array numbers in Ruby with examples

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to convert Class or Hash Object to JSON Object Ruby| Ruby on Rails By Example

How to remove duplicate elements from an array in Ruby with examples

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example