Skip to content

Instantly share code, notes, and snippets.

@joho
Created May 20, 2009 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joho/114594 to your computer and use it in GitHub Desktop.
Save joho/114594 to your computer and use it in GitHub Desktop.
i needed handy little chunks of my array
require 'test/unit'
class Array
def in_chunks_of(size_of_chunks)
if size_of_chunks >= length
[self]
else
[self[0, size_of_chunks]] + self[size_of_chunks, length].in_chunks_of(size_of_chunks)
end
end
end
class TestArrayInChunks < Test::Unit::TestCase
def test_chunking_equal_to_size
assert_equal [1, 2].in_chunks_of(2), [[1, 2]]
end
def test_chunk_greater_than_size
assert_equal [1, 2].in_chunks_of(4), [[1, 2]]
end
def test_even_chunks
assert_equal [1, 2, 3, 4].in_chunks_of(2), [[1, 2], [3, 4]]
end
def test_more_than_two_chunks
assert_equal [1, 2, 3, 4, 5, 6].in_chunks_of(2), [[1, 2], [3, 4], [5, 6]]
end
def test_more_than_two_chunks_with_remainder
assert_equal [1, 2, 3, 4, 5, 6, 7].in_chunks_of(2), [[1, 2], [3, 4], [5, 6], [7]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment