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.
Given an array of n non-negative integers. Choose three indices i.e. (0 <= index_1 <= index_ 2<= index_3 <= n) from the array to make four subsets such that the term sum(0, index_1) – sum(index_1, index_2) + sum(index_2, index_3) – sum(index_3, n) is maximum possible.
The split() function in NumPy is used to split an input array into multiple subarrays as specified by an integer value.
Sometimes partition is a good way to do things like that:
(1..6).partition { |v| v.even? } #=> [[2, 4, 6], [1, 3, 5]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With