如何交换散列中的键和值?
我有以下内容:
{:a=>:one, :b=>:two, :c=>:three}
我想转化成:
{:one=>:a, :two=>:b, :three=>:c}
使用map
似乎相当乏味.有更短的解决方案吗?
如何交换散列中的键和值?
我有以下内容:
{:a=>:one, :b=>:two, :c=>:three}
我想转化成:
{:one=>:a, :two=>:b, :three=>:c}
使用map
似乎相当乏味.有更短的解决方案吗?
Ruby有一个Hash的helper方法,可以让你把Hash当作是反向的(本质上是通过允许你通过值访问键):
{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
将丢弃除最后一次出现的值以外的所有值(因为它将在迭代期间不断替换该键的新值).同样,key
只返回第一个匹配项:
{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 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
注意:这个带有测试的代码现在是on GitHub.
或者:
class Hash
def safe_invert
self.each_with_object({}){|(k,v),o|(o[v]||=[])<<k}
end
end