本文介绍了在密钥中交换密钥和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 在Ruby中,如何交换Hash上的键和值? 假设我有以下哈希: {:a =>:one,:b =>:two,:c =>:three} 我想转换成: { :one =>:a,:two =>:b,:three =>:c} 使用地图似乎相当乏味。是否有更简单的解决方案?解决方案 Ruby有一个散列帮助方法,可以让你像对待散列那样对待散列。 {a:1,b:2,c:3} .key(1) => :a 如果您想保留倒排散列,那么Hash#invert 适用于大多数情况。 {a:1,b:2,c:3} .invert => {1 => a,2 => b,3 => c} BUT ... 如果您有重复的值, invert 将放弃所有但你最后的价值。同样,键只会返回第一个匹配项。 {a:1,b:2,c:2} .key(2) => :b {a:1,b:2,c:2} .invert => {1 =>:a,2 =>:c} 是独一无二的,你可以使用 Hash#invert 如果不是,那么你可以将所有的值保存为一个数组,如下所示: class Hash #like invert but no 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 ),出于| 出[值] || = [] 出[值]<< key end end end 注意:测试现在此处。 或者简而言之... class Hash def safe_invert self.each_with_object({}){|(k,v),o |(o [v] || = []) end 结束 In Ruby, how do I swap keys and values on a Hash?Let's say I have the following Hash:{:a=>:one, :b=>:two, :c=>:three}That I want to transform into:{:one=>:a, :two=>:b, :three=>:c}Using a map seems rather tedious. Is there a shorter solution? 解决方案 Ruby has a helper method for hash that lets you treat a hash as if it was inverted. {a: 1, b: 2, c: 3}.key(1)=> :aIf 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}BUT...If you have duplicate values, invert will discarding all but the last of your values. 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}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 endendNote: This code with tests is now here.Or in short...class Hash def safe_invert self.each_with_object({}){|(k,v),o|(o[v]||=[])<<k} endend 这篇关于在密钥中交换密钥和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-11 09:33