Ruby – Return a single key from a Hash

hashkeyruby

I would like to know how to return a specific key from a Hash?

Example:

moves = Hash["Kick", 100, "Punch", 50]

How would I return the first key "Kick" from this Hash?

NOTE: I'm aware that the following function will return all keys from the hash but I'm just interested in returning one key.

moves.keys #=> ["Kick", "Punch"]

Best Solution

You can use:

first_key, first_value = moves.first

Or equivalently:

first_key = moves.first.first

Quite nice too:

first_key = moves.each_key.first

The other possibility, moves.keys.first will build an intermediary array for all keys which could potentially be very big.

Note that Ruby 1.8 makes no guarantee on the order of a hash, so the key you will get not always be the same. In Ruby 1.9, you will always get the same key ("Kick" in your example).