In Ruby, the key()
method of a hash returns the key for the first-found entry with the given value. The given value is passed as an argument to this method.
hash.key(value)
value
: This is the value whose key we want to find.
This method returns the key for the first-found entry with the value value
. Nil
is returned if no such value exists.
# 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"}# find key entries# and print resultsputs "#{h1.key(2)}\n" # twoputs "#{h2.key('Okwudili')}\n" # nameputs "#{h3.key(5)}" # nilputs "#{h4.key("Apple")}" # A
key()
method, along with some arguments, on the hashes to get some keys. Then, we print the results to the console.Note: Line 11 printed
nil
because no key had a value of5
.