Given the Array:
arr = ['a','a','b','b','b','a','c']
Is there a quick way in Ruby to remove repeated consecutive elements, but not all duplicate elements like arr.uniq would? The expected output would be:
['a','b','a','c']
Here's what I've tried. It is possible to iterate over the Array as follows, but what is the cleanest way to do this in Ruby?
def remove_repeats arr
new_arr = []
last_element = nil
arr.each do |x|
if last_element != x
new_arr << x
end
last_element = x
end
new_arr
end
arr = ['a','a','b','b','b','a','c','c']
puts remove_repeats(arr).join(',')
# => a,b,a,c