Ruby在Ruby中创建Hash自定义反转函数

时间:2013-07-20 16:46:53

标签: ruby arrays hash

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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}