有没有办法使用Ruby删除数组中的特定重复项?数组示例:
["hello", "removeme", "removeme", "hello", "testing"]
我只想删除该数组上的"removeme"
个副本.所需的输出为:
["hello", "removeme", "hello", "testing"]
有没有像这样的方法来获得想要的输出?
先谢谢你.
有没有办法使用Ruby删除数组中的特定重复项?数组示例:
["hello", "removeme", "removeme", "hello", "testing"]
我只想删除该数组上的"removeme"
个副本.所需的输出为:
["hello", "removeme", "hello", "testing"]
有没有像这样的方法来获得想要的输出?
先谢谢你.
对于根据块的返回值删除重复项的块,可以使用uniq
:
ary = ["hello", "removeme", "removeme", "hello", "testing"]
ary.uniq { |obj| obj.eql?('removeme') || Object.new }
#=> ["hello", "removeme", "hello", "testing"]
对于等于'removeme'
的元素,我们返回true
,对于其他所有元素('hello'
、'hello'
和'testing'
),我们返回一个新对象:(请注意不同的对象ID)
"hello" → #<Object:0x00007f9ab08590d8>
"removeme" → true
"removeme" → true
"hello" → #<Object:0x00007f9ab0858d68>
"testing" → #<Object:0x00007f9ab08589f8>
具有相同返回值的所有元素都被认为是重复的,即uniq
会将'removeme'
视为重复的,而将其他任何元素视为唯一的,而不考虑其实际值.这允许保留两个相同的'hello'
串.