红宝石:如何找到和阵列返回重复值? [英] Ruby: How to find and return a duplicate value in array?

查看:110
本文介绍了红宝石:如何找到和阵列返回重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

改编是一个字符串数组,例如: [你好,世界,堆栈,溢出,你好 又]

什么是检查改编有重复的,如果是,返回他们中的一个(无论哪个)轻松优雅的方式。

例如:

  [A,B,C,B,A]#=> A或B
[A,B,C]#=>零


解决方案

  A = [A,B,C,B,A]
a.detect {| E | a.count(E)> 1}

arr is array of strings, e.g.: ["hello", "world", "stack", "overflow", "hello", "again"].

What would be easy and elegant way to check if arr has duplicates, and if yes, return one of them (no matter which).

Examples:

["A", "B", "C", "B", "A"]    # => "A" or "B"
["A", "B", "C"]              # => nil

解决方案

a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }

这篇关于红宝石:如何找到和阵列返回重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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