"Example_Value"} example["Example_Key"] ...">

Is there a way to access keys from values?

If I print something like:

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

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

+4
source share
2 answers

Yes there is:

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

Check out the documentation Hash#key

Returns the key for a given value.. If the valuenot found, returns nil.

+3
source

You can create a hash that works differently:

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

Source: https://habr.com/ru/post/1548234/


All Articles