ruby - Slice array when element reached -
lets have array so: ['x','cat', 'dog', 'x', 'dolphin', 'cougar', 'whale']
i don't know length of array or when 'x' occur. when reach 'x' want push following elements new array until reach next element includes?('x').
the desired output be: [['cat', 'dog']['dolphin','cougar', 'whale']]
how can achieve this?
good old enumerable#reduce handy many things:
def split_array_by_item(array, item) array.reduce([]) |memo, x| memo.push([]) if (x == item) || memo.empty? memo[-1].push(x) unless x == item memo end end = ['x', 'cat', 'dog', 'x', 'dolphin', 'cougar', 'whale'] split_array_by_item(a, 'x') # => [["cat", "dog"], ["dolphin", "cougar", "whale"]] [edit] also:
def split_array_by_item(array, item) array.chunk{|x|x==item}.reject(&:first).map(&:last) end
Comments
Post a Comment