如果值重复,则从散列的散列中删除散列 [英] Remove hash from hash of hashes if value is duplicated

查看:55
本文介绍了如果值重复,则从散列的散列中删除散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的散列值

params = {collection_permissions_attributes: {'0' => {:collection_id => '1'},
                                                   '2' => {:collection_id => '1'},
                                                   '3' => {:collection_id => '4'}}}

如何从 collection_permissions_attributes 项目中完全删除散列包含重复值的项目?所以从上面的哈希我想:

How can I remove completely from collection_permissions_attributes item which hash contains duplicated value? So from hash above I would like to have:

params = { collection_permissions_attributes: {'0' => {:collection_id => '1'},
                                                   '3' => {:collection_id => '4'}}}

提前致谢!

推荐答案

这是另一种方法,但它需要 Ruby 1.9+,因为它取决于散列元素的顺序.

Here's another way, but it requires Ruby 1.9+, as it depends on the order of the hash's elements.

代码

newams = {collection: ams[:collection].sort.reverse.to_h.invert.invert}
  #=> {:collection=>{"3"=>{:collection_id=>"4"}, "0"=>{:collection_id=>"1"}}}

如果出于某种原因希望散列元素按键顺序排列,可以通过添加更多操作来实现,如说明"部分末尾所述.

If for some reason it is desired that the hash elements be in key order, that can be achieved by adding a few more operations, as explained at the end of the "explanation" section.

说明

ams = {collection: {'0' => {:collection_id => '1'},
                    '2' => {:collection_id => '1'},
                    '3' => {:collection_id => '4'}}}

首先,将hash元素按key降序重新排序,这样当两个或多个元素的值相同时,只保留key值最小的元素.要做到这一点,然后重建散列,需要三个步骤:

First, reorder the hash elements in descending key order, so that when two or more elements have the same value, only the element having the smallest key value will be kept. To do this and then reconstitute the hash, three steps are required:

a = ams[:collection].sort
  #=> [["0", {:collection_id=>"1"}], ["2", {:collection_id=>"1"}],
  #    ["3", {:collection_id=>"4"}]] 
b = a.reverse
  #=> [["3", {:collection_id=>"4"}], ["2", {:collection_id=>"1"}],
  #    ["0", {:collection_id=>"1"}]] 
c = b.to_h
  #=> {"3"=>{:collection_id=>"4"}, "2"=>{:collection_id=>"1"},
  #    "0"=>{:collection_id=>"1"}} 

接下来,我们反转散列,使键值和值键.因为哈希不能有重复的键,这消除了重复:

Next, we invert the hash, making the keys values and the values keys. Because hashes cannot have duplicate keys, this eliminates the duplicates:

d = c.invert
  #=> {{:collection_id=>"4"}=>"3", {:collection_id=>"1"}=>"0"}

最后,反转:

e = d.invert
  #=> {"3"=>{:collection_id=>"4"}, "0"=>{:collection_id=>"1"}} 

散列元素可以像这样按键顺序(如果需要)重新排序:

The hash elements can reordered in key order (should that be desired) like this:

e.to_a.reverse.to_h
  #=> {"0"=>{:collection_id=>"1"}, "3"=>{:collection_id=>"4"}} 

这篇关于如果值重复,则从散列的散列中删除散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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