I'm looking to make a method which detects if the following value in an array is a duplicate, and deletes it if so. It should work for both strings and integers.
For example, given the Array:
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
Return:
arr = ["A", "B", "C", "c", "A", "D"]
I tried creating an empty Array a, and shovelling the values in, providing the following value was not equal to the current one. I attempted this like so:
arr.each do |x|
following_value = arr.index(x) + 1
a << x unless x == arr[following_value]
end
Unfortunately, instead of shovelling one of the duplicate values into the array, it shovelled neither.
arr = ["A", "C", "c", "A"]
Can anybody help? Bonus points for telling me exactly what went wrong with my method.
Thanks!
["A", "B", "B", "C", "c", "A", "D", "D"].uniq?A, as I understand OP wants to take element if next isn't equal to itarr.index(x)will always return the index of the first matching element. Please note my answer for details