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.
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.
There are multiple ways we can check key exists in a hash.
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
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
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
To summarize, There are multiple ways to check key exist in hash object with examples.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts