Assuming one can have arrays with consecutive duplicate elements, I'm looking for a way to turn this array:
['A', 'B', 'C', 'C', 'D', 'D', 'F']
into this:
[['A', 'B', 'C'], ['C', 'D'], ['D','F']]
Please mind that for my particular case an array may not have more than 2 consecutive duplicate elements.
Enumerable#slice_when does that.
arr = ['A', 'B', 'C', 'C', 'D', 'D', 'F']
p arr.slice_when{|a,b| a==b}.to_a
# =>[["A", "B", "C"], ["C", "D"], ["D", "F"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With