删除 Ruby 数组中冗余或重复的元组 [英] Remove redundant or duplicate tuples in Ruby array

查看:37
本文介绍了删除 Ruby 数组中冗余或重复的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象以下 Ruby 数组:

Imagine the following Ruby array:

[9, 9, 5, 5, 5, 2, 9, 9]

删除冗余元组的最简单方法是什么,产生如下输出:

What's the easiest way of removing redundant tuples, producing an output like the following:

[9, 5, 2, 9]

uniq 不正确,因为它正在检查整个数组.输入的顺序很重要,必须保持.对此有直接的方法吗?

uniq is not correct because it's examining the entire array. The ordering of the input is important and must be kept. Is there a straightforward approach to this?

谢谢!

推荐答案

我会使用 Enumerable#chunk

2.0.0-p0 :001 > a = [9, 9, 5, 5, 5, 2, 9, 9]
 => [9, 9, 5, 5, 5, 2, 9, 9] 
2.0.0-p0 :002 > a.chunk { |e| e }.map(&:first)
 => [9, 5, 2, 9]

这篇关于删除 Ruby 数组中冗余或重复的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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