Return a single key from a Hash?
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"]
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).
moves.keys[0]
will give you the first key. You can get all keys by changing the argument passed (0, 1,...etc)
moves.keys.first
will accomplish that.
精彩评论