How to split an array on duplicate elements in Ruby

Viewed 135

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.

2 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"]]
arr = ['A', 'B', 'C', 'C', 'D', 'D', 'F']

arr.chunk_while(&:!=).to_a
  #=> [["A", "B", "C"], ["C", "D"], ["D", "F"]]

See Enumerable#chunk_while.

Old-fashioned way:

arr.each_with_object([[]]) do |s,a|
  if s == a.last.last
    a << [s]
  else
    a.last << s
  end
end
  #=> [["A", "B", "C"], ["C", "D"], ["D", "F"]]
Related