我如何获得哈希在Ruby中数组的独特元素?

编程入门 行业动态 更新时间:2024-10-26 04:29:13
本文介绍了我如何获得哈希在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中数组的独特元素?

本文发布于:2023-10-28 05:28:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何获得   元素   独特   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!