我如何在Ruby中一个阵列内检测重复值? [英] How do I detect duplicate values within an array in Ruby?

查看:128
本文介绍了我如何在Ruby中一个阵列内检测重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组,看起来像:

Say I have an array that looks like:

a = [cat, dog, cat, mouse, rat, dog, cat]

如何通过我做的周期,并做一些重复 - 例如说它们删除?

How do I cycle through that, and do something with duplicates - e.g. say delete them?

在换句话说,如果我做了 a.each做| I | ,我怎么评价[0]反对[1],A [2] ,一个[3] ...然后当我找到了一个我想,说[2]在这起案件的第一个副本,然后我把它推到一个堆栈或将其删除或东西。

In other words, if I did a.each do |i|, how do I evaluate a[0], against a[1], a[2], a[3]...and then when I find the one I want, say a[2] in this case has the first duplicate, I then push it to a stack or remove it or something.

我知道如何评价钥匙,与价值......但我怎么在同一阵列中评估对彼此价值观?

I know how to evaluate keys, versus values...but how do I evaluate values against each other within the same array?

感谢。

推荐答案

您可以创建一个散列的时候任何元素重复门店数量。因此,在遍历数组只有一次。

You can create a hash to store number of times any element is repeated. Thus iterating over array just once.

h = Hash.new(0)
['a','b','b','c'].each{ |e| h[e] += 1 }

应该导致

 {"a"=>1, "b"=>2, "c"=>1}

这篇关于我如何在Ruby中一个阵列内检测重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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