Skip to content

Instantly share code, notes, and snippets.

@r00k
Created June 16, 2009 20:25
Show Gist options
  • Save r00k/130874 to your computer and use it in GitHub Desktop.
Save r00k/130874 to your computer and use it in GitHub Desktop.
class Array
# Split an array into 10 pieces, yield 1/10th and the other 9/10ths. Do this 10 times, returning a distinct
# (no overlaps) 1/10th slice each time.
def iterate_by_tenths(&block)
self.each_slice((self.length / 10).ceil) do |tenth|
yield(tenth, self - tenth)
end
end
end
# Tests
def test_iterate_by_tenths
array = (1..10).to_a
concatenated_tenths = []
array.iterate_by_tenths do |tenth, rest|
assert_equal 1, tenth.size
assert_equal 9, rest.size
concatenated_tenths += tenth
end
assert_equal array, concatenated_tenths
end
def test_iterate_by_tenths_not_even
array = (1..25).to_a
concatenated_tenths = []
array.iterate_by_tenths do |tenth, rest|
# Have to handle special case of last element
if tenth == [25]
assert_equal 1, tenth.size, tenth
assert_equal 24, rest.size, rest
else
assert_equal 3, tenth.size, tenth
assert_equal 22, rest.size, rest
end
concatenated_tenths += tenth
end
assert_equal array, concatenated_tenths
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment