Overview
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.
Syntax
hash.key(value)
Parameters
value
: This is the value whose key we want to find.
Return value
This method returns the key for the first-found entry with the value value
. Nil
is returned if no such value exists.
Code example
# create hashes
h1 = {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 results
puts "#{h1.key(2)}\n" # two
puts "#{h2.key('Okwudili')}\n" # name
puts "#{h3.key(5)}" # nil
puts "#{h4.key("Apple")}" # A
Code explanation
- Lines 2–5: We create several hashes.
- Lines 9–12: We invoke the
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
.