从Ruby中删除数组中的重复元素

本文翻译自:Remove duplicate elements from array in Ruby

I have a Ruby array which contains duplicate elements. 我有一个包含重复元素的Ruby数组。

array = [1,2,2,1,4,4,5,6,7,8,5,6]

How can I remove all the duplicate elements from this array while retaining all unique elements without using for-loops and iteration? 如何在不使用for循环和迭代的情况下保留所有唯一元素的同时从此数组中删除所有重复元素?


#1楼

参考:https://stackoom.com/question/Z6Iz/从Ruby中删除数组中的重复元素


#2楼

If someone was looking for a way to remove all instances of repeated values, see this question . 如果有人正在寻找删除重复值的所有实例的方法,请参阅此问题

a = [1, 2, 2, 3]
counts = Hash.new(0)
a.each { |v| counts[v] += 1 }
p counts.select { |v, count| count == 1 }.keys # [1, 3]

#3楼

You can also return the intersection. 你也可以返回十字路口。

a = [1,1,2,3]
a & a

This will also delete duplicates. 这也将删除重复项。


#4楼

Just another alternative if anyone cares. 如果有人关心,只是另一种选择。

You can also use the to_set method of an array which converts the Array into a Set and by definition, set elements are unique. 您还可以使用数组的to_set方法将Array转换为Set,根据定义,set元素是唯一的。

[1,2,3,4,5,5,5,6].to_set => [1,2,3,4,5,6]

#5楼

Try with XOR Operator in Ruby: 尝试使用Ruby中的XOR运算符:

a = [3,2,3,2,3,5,6,7].sort!

result = a.reject.with_index do |ele,index|
  res = (a[index+1] ^ ele)
  res == 0
end

print result

#6楼

array = array.uniq

The uniq method removes all duplicate elements and retains all unique elements in the array. uniq方法删除所有重复元素并保留数组中的所有唯一元素。

One of many beauties of Ruby language. Ruby语言的众多美女之一。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值