I was looking for an Array equivalent String#split
in Ruby Core, and was surprised to find that it did not exist. Is there a more elegant way than the following to split an array into sub-arrays based on a value?
class Array
def split( split_on=nil )
inject([[]]) do |a,v|
a.tap{
if block_given? ? yield(v) : v==split_on
a << []
else
a.last << v
end
}
end.tap{ |a| a.pop if a.last.empty? }
end
end
p (1..9 ).to_a.split{ |i| i%3==0 },
(1..10).to_a.split{ |i| i%3==0 }
#=> [[1, 2], [4, 5], [7, 8]]
#=> [[1, 2], [4, 5], [7, 8], [10]]
Edit: For those interested, the "real-world" problem which sparked this request can be seen in this answer, where I've used @fd's answer below for the implementation.