Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a single key from a Hash?

Tags:

ruby

key

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"]
like image 855
Dru Avatar asked Jul 05 '11 22:07

Dru


People also ask

How do you get the key of a hash in Ruby?

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.

How do you return a hash in Ruby?

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.

How do I find the hash key?

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+.


2 Answers

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).

like image 67
Marc-André Lafortune Avatar answered Oct 16 '22 21:10

Marc-André Lafortune


    moves.keys[0] 

will give you the first key. You can get all keys by changing the argument passed (0, 1,...etc)

like image 44
rightskewed Avatar answered Oct 16 '22 20:10

rightskewed