1

Ruby 类 Hash 具有方法“invert”,它可以在键和值之间“反转”并删除相同的键(在我们的例子中是:“1=>:a”)。h = {a: 1, b: 2, c: 1} => {:a=>1, :b=>2, :c=>1} h.invert => {1=>:c, 2= >:b}

如何实现自定义哈希方法“c_invert”,它将返回第一对(不是最后一个)重复键 => 值?示例:

> h = {a: 1, b: 2, c: 1} 
=> {:a=>1, :b=>2, :c=>1} 
> h.c_invert 
=> {1=>:a, 2=>:b} 
4

2 回答 2

3
class Hash
  def c_invert
    Hash[to_a.reverse].invert
  end
end

或者

class Hash
  def c_invert
    Hash[to_a.reverse.map(&:reverse)]
  end
end
于 2013-07-20T16:51:36.827 回答
0
h =  {:d =>1,:a=>1, :b=> 2, :c=>1}
Hash[h.map(&:reverse).reverse]
# => {1=>:d, 2=>:b}

h = {a: 1, b: 2, c: 1} 
Hash[h.map(&:reverse).reverse]
# => {1=>:a, 2=>:b}
于 2013-07-20T17:00:34.300 回答