Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into sub-arrays based on value

Tags:

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.

like image 564
Phrogz Avatar asked Jan 26 '11 00:01

Phrogz


People also ask

How do you split an array into 4 Subarrays?

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.

Which of the following function is used to split array into subarrays?

The split() function in NumPy is used to split an input array into multiple subarrays as specified by an integer value.


1 Answers

Sometimes partition is a good way to do things like that:

(1..6).partition { |v| v.even? }  #=> [[2, 4, 6], [1, 3, 5]] 
like image 136
scaryguy Avatar answered Sep 19 '22 04:09

scaryguy