Ruby 是否有方法从值访问键?

Ruby 是否有方法从值访问键?,ruby,hash,key,Ruby,Hash,Key,如果我键入如下内容: example = {"Example_Key" => "Example_Value"} example["Example_Key"] 解释器将返回值“示例值”。有没有办法输入值并获取密钥?有,有: example = {"Example_Key" => "Example_Value"} example.key "Example_Value" # => "Example_Key" 查看文档 返回给定值出现的键。如果未找到值,则返回nil 您可以创建另一

如果我键入如下内容:

example = {"Example_Key" => "Example_Value"}
example["Example_Key"]
解释器将返回值
“示例值”
。有没有办法输入值并获取密钥?

有,有:

example = {"Example_Key" => "Example_Value"}
example.key "Example_Value" # => "Example_Key"
查看文档

返回给定值出现的。如果未找到,则返回
nil


您可以创建另一种工作方式的哈希:

inverted = example.invert # => {"Example_Value"=>"Example_Key"}
inverted["Example_Value"] # => "Example_Key"
请注意,a)它返回“一个事件”,而不是“事件”或“所有事件”(可以有多个),b)它必须搜索该键,即它是O(n)。如果经常需要在两个方向上查找,则不应使用贴图,而应使用bimap/bidimap。