Ruby has a helper method for Hash that lets you treat a Hash as if it was inverted (in essence, by letting you access keys through values):{a: 1, b: 2, c: 3}.key(1)=> :a如果您想保留反向哈希,请 Hash#invert 在大多数情况下都可以使用:If you want to keep the inverted hash, then Hash#invert should work for most situations:{a: 1, b: 2, c: 3}.invert=> {1=>:a, 2=>:b, 3=>:c} 但是... 如果您有重复的值,则invert将丢弃所有值(最后一次出现)(因为它将在迭代过程中继续替换该键的新值).同样,key将仅返回第一个匹配项:If you have duplicate values, invert will discard all but the last occurrence of your values (because it will keep replacing new value for that key during iteration). Likewise, key will only return the first match: {a: 1, b: 2, c: 2}.key(2)=> :b{a: 1, b: 2, c: 2}.invert=> {1=>:a, 2=>:c}因此,如果您的值唯一,则可以使用Hash#invert.如果没有,则可以将所有值保留为数组,如下所示:So, if your values are unique you can use Hash#invert. If not, then you can keep all the values as an array, like this:class Hash # like invert but not lossy # {"one"=>1,"two"=>2, "1"=>1, "2"=>2}.inverse => {1=>["one", "1"], 2=>["two", "2"]} def safe_invert each_with_object({}) do |(key,value),out| out[value] ||= [] out[value] << key end endend注意:带有测试的代码现在在GitHub上 . Note: This code with tests is now on GitHub. 或者:class Hash def safe_invert self.each_with_object({}){|(k,v),o|(o[v]||=[])<<k} endend 这篇关于如何在哈希中交换键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-13 18:55