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"]
hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.
new : This method returns a empty hash. In the first form the access return nil. If obj is specified then, this object is used for all default values. If a block is specified, then it will be called by the hash key and objects and return the default value.
To find a hash key by it's value, i.e. reverse lookup, one can use Hash#key . It's available in Ruby 1.9+.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With