In Ruby, the hash.key?()
method is used to check if a given key exists in a hash.
hash.key?(keyToFind)
This method takes keyToFind
as a parameter. It is the key we want to check.
It returns a boolean
value. It returns true
if the key exists. Otherwise, it returns false
.
# create hashesh1 = {one: 1, two: 2, three: 3}h2 = {name: "okwudili", stack: "ruby"}h3 = {"foo": 0, "bar": 1}h4 = {M:"Mango", A: "Apple", B: "Banana"}# check if key exists# and print resultsputs h1.key?(:one)puts h2.key?(:name)puts h3.key?(:foo)puts h4.key?(:C)
Lines 2–5: We create some hashes.
Lines 9–12: We check if some keys exist in the hashes. Next, we print the results to the console.