Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array on duplicate elements in Ruby

Tags:

arrays

ruby

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.

like image 904
stratis Avatar asked May 31 '26 05:05

stratis


1 Answers

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"]]
like image 119
steenslag Avatar answered Jun 01 '26 22:06

steenslag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!