2013-07-20 71 views
1

Ruby class哈希有方法「反轉」,它在鍵和值之間進行「反轉」並刪除相同的鍵(在我們的例子中爲:「1 =>:a」)。 h.invert => {1 =>:1:0:1:0: c,2 =>:b}Ruby在Ruby中創建哈希自定義反轉函數

如何實現自定義哈希方法「c_invert」,它會返回非常優先(而非最後一個)對重複鍵=>值? Exapmle:

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

回答

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 
+0

澤,感謝快速反饋! –

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}