Question: 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!

Answer: 
First at all, here is simpler solution:

```
> arr.delete_if.with_index { |e, ind| e == arr[ind+1] }
#=> ["A", "B", "C", "c", "A", "D"]

```

But, this solution will mutate `arr`.
Here are one-line solutions without mutates:

```
arr.each_with_index.with_object([]) { |(e, ind), res| res << e if e != arr[ind+1] }
arr.each_with_object([]) { |e, res| res << e if res.last != e }

```

Your problem in this line: `a << x unless x == arr[following_value]`
You say: put this `element` into `result` if `next element` isn't equal to it. So, instead, you can say something like: *put this element to result if the last element of the result isn't equal to it*:

```
arr.each do |x|
  a << x unless a.last == x
end

```
I would use [select](https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-select), so you could do something like:

```
a = ["A", "B", "B", "C", "c", "A", "D", "D"]

# without mutation
b = a.select.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "B", "C", "c", "A", "D", "D"]
b #=> ["A", "B", "C", "c", "A", "D"]

# with mutation
a.select!.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "C", "c", "A", "D"]

```

BTW your method is not working because `arr.index(x)` [returns index of first object for which block is true](https://apidock.com/ruby/Array/index):

```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
arr.each do |x|
  puts "#{x} has index #{arr.index(x)}"
end
A has index 0
B has index 1
B has index 1 # you were expecting 2
C has index 3
c has index 4
A has index 0 # you were expecting 5
D has index 6
D has index 6 # you were expecting 7

```