Search code examples
arraysrubysplitsub-array

ruby - split an array into sub arrays when a value changes and ignore/delete that value


I want to split the following array into sub arrays so that the sub-arrays start and finish when the 1's start and finish...

a=[1,1,0,0,1,0,1,1,1]

so I end up with this as a new array...

=>  [[1,1],[1],[1,1,1]]

anyone got any ideas...?


Solution

  • Simplest and most readable way would probably be:

    a.chunk {|x| x==1 || nil}.map(&:last)
      #=> [[1, 1], [1], [1, 1, 1]]
    

    If you were okay with using Ruby on Rails, you can use an even simpler solution:

    a.split(0).reject(&:empty?)
      #=> [[1, 1], [1], [1, 1, 1]]