如何在哈希中交换键和值 [英] How to swap keys and values in a hash

查看:101
本文介绍了如何在哈希中交换键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何交换哈希中的键和值?

How do I swap keys and values in a Hash?

我有以下哈希值:

{:a=>:one, :b=>:two, :c=>:three}

我要转换成的

:

that I want to transform into:

{:one=>:a, :two=>:b, :three=>:c}

使用map似乎很乏味.有更短的解决方案吗?

Using map seems rather tedious. Is there a shorter solution?

推荐答案

Ruby为Hash提供了一个辅助方法,该方法可让您将Hash视为已倒置(本质上是让您通过值访问键):

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

如果您想保留反向哈希,请

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
  end
end

注意:带有测试的代码现在在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}
  end
end

这篇关于如何在哈希中交换键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆