I know this is an old question, but I think that the original seeker intended to find the key when he does NOT know what it is; For example, when iterating through a hash.
A few other ways to get your hash key:
Given a hash definition:
myhash = Hash.new myhash["a"] = "Hello, " myhash["b"] = "World!"
The reason your first attempt failed:
So, if you want to capture the key when repeating through a hash:
#when pulling each THEN the code block is always run on each result. myhash.each_pair {|key,value| puts "#{key} = #{value}"}
And if you are just in one ship and you want:
Get the key for this key (not sure why, since you already know the key):
myhash.each_key {|k| puts k if k == "a"}
Get the key for the given value:
myhash.each_pair {|k,v| puts k if v == "Hello, "}
source share