ruby - Split array into sub-arrays based on value -


i looking array equivalent string#split in ruby core, , surprised find did not exist. there more elegant way following split array sub-arrays based on value?

class array   def split( split_on=nil )     inject([[]]) |a,v|       a.tap{         if block_given? ? yield(v) : v==split_on           << []         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: interested, "real-world" problem sparked request can seen in this answer, i've used @fd's answer below implementation.

i tried golfing bit, still not single method though:

(1..9).chunk{|i|i%3==0}.reject{|sep,ans| sep}.map{|sep,ans| ans} 

or faster:

(1..9).chunk{|i|i%3==0 || nil}.map{|sep,ans| sep&&ans}.compact 

also, enumerable#chunk seems ruby 1.9+, close want.

for example, raw output be:

(1..9).chunk{ |i|i%3==0 }.to_a                                        => [[false, [1, 2]], [true, [3]], [false, [4, 5]], [true, [6]], [false, [7, 8]], [true, [9]]] 

(the to_a make irb print nice, since chunk gives enumerator rather array)


edit: note above elegant solutions 2-3x slower fastest implementation:

module enumerable   def split_by     result = [a=[]]     each{ |o| yield(o) ? (result << a=[]) : (a << o) }     result.pop if a.empty?     result   end end 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -