有没有办法使用 Ruby 删除数组中的特定字符串?示例数组:
["hello", "removeme", "removeme", "hello", "testing"]
我只想删除该数组上的重复项
removeme
。期望的输出是:
["hello", "removeme", "hello", "testing"]
有没有像这样的方法来获得所需的输出?
["hello", "removeme", "removeme", "hello", "testing"].uniq('removeme')
提前致谢。
假设给定的数组如下。
arr = ["hello", "removeme", "hello", "goodbye", "removeme", "testing"]
如果
arr
的元素顺序不重要,你可以这样写。
def removem(arr, to_remove)
a = arr.dup
y = a.delete(to_remove)
y.nil? ? a : (a << to_remove)
end
removem(arr, "removeme") #=> ["hello", "hello", "goodbye", "testing", "removeme"]
#=> ["hello", "hello", "goodbye", "testing", "removeme"]
removem(arr, "goodbye")
#=> ["hello", "removeme", "hello", "removeme", "testing", "goodbye"]
removem(arr, "missing")
#=> ["hello", "removeme", "hello", "goodbye", "removeme", "testing"]
在每个例子中
arr
不变。
如果只保留给定值的第一个实例,可以使用以下方法。
def removem(arr, to_remove)
first_found = false
indices_to_remove = []
arr.each_index do |i|
next unless if arr[i] == to_remove
if first_found
indices_to_remove << i
else
first_found = true
end
end
return arr if indices_to_remove.empty?
arr.values_at((0..arr.size - 1).to_a - indices_to_remove)
end
removem(arr, "removeme")
#=> ["hello", "removeme", "hello", "goodbye", "testing"]
removem(arr, "goodbye")
#=> ["hello", "removeme", "hello", "goodbye", "removeme", "testing"]
removem(arr, "missing")
#=> ["hello", "removeme", "hello", "goodbye", "removeme", "testing"]
在每个例子中
arr
不变。