How to split a Ruby array into subarrays of unequal size using a delimiter

I have the following array:

arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]

Without changing the order of the values, I need to subdivide arrinto smaller arrays in each case 0, so that the result is:

arr = [ [0, 1, 1, 2, 3, 1], [0], [0, 1] ]

If there arrwas a string, I could use .split("0")and then add a separator to each subarray. What would be the most efficient equivalent .split()in plain Ruby for arrays?

+4
source share
2 answers

Enumerable#slice_before does this exact thing:

arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
p arr.slice_before(0).to_a
# => [[0, 1, 1, 2, 3, 1], [0], [0, 1]]

Take a look at repl.it: https://repl.it/FBhg

+4
source

ActiveSupport Array # Ruby, :

class Array
  def split(value = nil)
    arr = dup
    result = []
    if block_given?
      while (idx = arr.index { |i| yield i })
        result << arr.shift(idx)
        arr.shift
      end
    else
      while (idx = arr.index(value))
        result << arr.shift(idx)
        arr.shift
      end
    end
    result << arr
  end
end

# then, using the above to achieve your goal:
arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
arr.split(0).map { |sub| sub.unshift(0) }
# => [[0], [0, 1, 1, 2, 3, 1], [0], [0, 1]] 

, (split prepend) - , , ( - , split).

? slice_before.

, ? compact , [0].

, , ?

/0+/?

0

Source: https://habr.com/ru/post/1665898/


All Articles