Dor-Ron
Dor-Ron

Reputation: 1807

Is there a way to access the keys from the values?

If I type something like:

example = {"Example_Key" => "Example_Value"}
example["Example_Key"]

the interpreter will return "Example_Value", which is the value. Is there a way to enter a value and get the key?

Upvotes: 3

Views: 85

Answers (2)

sawa
sawa

Reputation: 168269

You can create a hash that works the other way:

inverted = example.invert # => {"Example_Value"=>"Example_Key"}
inverted["Example_Value"] # => "Example_Key"

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118299

Yes, there is :

example = {"Example_Key" => "Example_Value"}
example.key "Example_Value" # => "Example_Key"

Check out the documentation Hash#key

Returns the key of an occurrence of a given value. If the value is not found, returns nil.

Upvotes: 3

Related Questions