我如何获得哈希在Ruby中数组的独特元素? [英] How do I get the unique elements from an array of hashes in Ruby?

查看:154
本文介绍了我如何获得哈希在Ruby中数组的独特元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有散列的数组,我想的唯一值出来。调用 Array.uniq 并没有给我什么,我期待。

I have an array of hashes, and I want the unique values out of it. Calling Array.uniq doesn't give me what I expect.

a = [{:a => 1},{:a => 2}, {:a => 1}]
a.uniq # => [{:a => 1}, {:a => 2}, {:a => 1}]

在哪里我的预期:

Where I expected:

[{:a => 1}, {:a => 2}]

在网上搜索的时候,我并没有拿出一个解决方案,我很高兴。伙计们建议重新定义 Hash.eql? Hash.hash ,因为这是什么阵列。 uniq的正在查询。

In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining Hash.eql? and Hash.hash, since that is what Array.uniq is querying.

编辑:
凡我在现实世界中碰到了这一点,散列是稍微复杂一些。它们是已解析的JSON即有多个字段,其中一些的值分别为哈希以及结果。我有,我想筛选出唯一值这些结果的数组。

Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values.

我不喜欢重新定义 Hash.eql? Hash.hash 的解决方案,因为我要么必须重新定义哈希全球范围内,或者重新定义它在我的阵列中的每个条目。更改哈希的定义,每个条目会很麻烦,尤其是有可能嵌套每个条目的内部哈希。

I don't like the redefine Hash.eql? and Hash.hash solution, because I would either have to redefine Hash globally, or redefine it for each entry in my array. Changing the definition of Hash for each entry would be cumbersome, especially since there may be nested hashes inside of each entry.

修改哈希在全球有一定的潜力,尤其是如果它被暂时完成。我想建一个类或辅助函数包裹节省掉旧的定义,并恢复他们,但我认为这增加了更多的复杂性比实际需要。

Changing Hash globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed.

使用似乎是一个很好的选择,以重新定义哈希

Using inject seems like a good alternative to redefining Hash.

推荐答案

我能得到我想要的东西通过调用

I can get what I want by calling inject

a = [{:a => 1},{:a => 2}, {:a => 1}]
a.inject([]) { |result,h| result << h unless result.include?(h); result }

这将返回:

[{:a=>1}, {:a=>2}]

这篇关于我如何获得哈希在Ruby中数组的独特元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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