Well, this seems to be a tasty dish. I took some liberty with your minimal spec, but you should see the first test for the usage that maps to your example.
#!/usr/bin/ruby -w
class Array
def split_when
result = []
each do |element|
result[-1] << element
if block_given? ? yield(element) : element
result <<
end
end
result.pop if result.last.empty?
result
end
end
if File.expand_path($0) == File.expand_path(__FILE__)
require 'test/unit'
class SplitWhenTest < Test::Unit::TestCase
def setup
h1 = { :cue => false }
h2 = { :cue => false }
h3 = { :cue => true }
h4 = { :cue => false }
h5 = { :cue => true }
@ary = [ h1, h2, h3, h4, h5 ]
@expected = [ [h1, h2, h3], [h4, h5] ]
end
def test_example_from_email
assert_equal @expected, @ary.split_when {|e| e[:cue]}
end
def test_simple
original = [ false, true, false, false, true, true, false, true, false, true, false ]
expected = [[false, true],[false, false, true],[true],[false, true],[false, true],[false]]
assert_equal expected, original.split_when, "no block"
assert_equal expected, original.split_when {|e|e}, "simple block"
end
end
__END__
:code/ruby $ ./array_split_when.rb
Loaded suite ./array_split_when
Started
..
Finished in 0.000585 seconds.
2 tests, 3 assertions, 0 failures, 0 errors
-Rob
Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com