Last active
January 1, 2016 19:29
-
-
Save apeiros/8190494 to your computer and use it in GitHub Desktop.
Split an Array, similar to String#split
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def split(*separator, include_separator: false) | |
if separator.empty? | |
if !block_given? | |
return enum_for(__method__) if separator.empty? && !block_given? | |
end | |
elsif block_given? | |
raise ArgumentError, "Must either pass a block or a separator, not both" | |
else | |
separator = separator.first | |
end | |
current = [] | |
result = [] | |
if block_given? | |
each do |item| | |
if yield(item) | |
result << current | |
result << [item] if include_separator | |
current = [] | |
else | |
current << item | |
end | |
end | |
else | |
each do |item| | |
if separator == item | |
result << current | |
result << [item] if include_separator | |
current = [] | |
else | |
current << item | |
end | |
end | |
end | |
result << current unless current.empty? | |
result | |
end | |
end | |
if __FILE__ == $0 | |
require 'test/unit' | |
class ArraySplitTest < Test::Unit::TestCase | |
def test_all | |
assert_equal([[1], [2], [3]], [1,nil,2,nil,3].split(nil)) | |
assert_equal([[1], [2, 3], [3]], [1,nil,2,3,nil,3].split(nil)) | |
assert_equal([[1, 2], [4, 5], [7, 8], [10]], [*1..10].split { |e| e % 3 == 0 }) | |
assert_equal([], [].split { |e| e % 3 == 0 }) | |
assert_equal([[1], [nil], [2], [nil], [3]], [1,nil,2,nil,3].split(nil, include_separator: true)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment