Skip to content

Commit

Permalink
Merge pull request #12839 from kuldeepaggarwal/array_split
Browse files Browse the repository at this point in the history
Array#split preserving the calling array
  • Loading branch information
guilleiguaran committed Nov 11, 2013
2 parents b72304f + 1333994 commit 5b12213
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
4 changes: 2 additions & 2 deletions activesupport/lib/active_support/core_ext/array/grouping.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ def split(value = nil, &block)
results results
end end
else else
results, arr = [[]], self results, arr = [[]], self.dup
until arr.empty? until arr.empty?
if (idx = index(value)) if (idx = arr.index(value))
results.last.concat(arr.shift(idx)) results.last.concat(arr.shift(idx))
arr.shift arr.shift
results << [] results << []
Expand Down
18 changes: 12 additions & 6 deletions activesupport/test/core_ext/array_ext_test.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -212,18 +212,24 @@ def test_split_with_empty_array
end end


def test_split_with_argument def test_split_with_argument
assert_equal [[1, 2], [4, 5]], [1, 2, 3, 4, 5].split(3) a = [1, 2, 3, 4, 5]
assert_equal [[1, 2, 3, 4, 5]], [1, 2, 3, 4, 5].split(0) assert_equal [[1, 2], [4, 5]], a.split(3)
assert_equal [[1, 2, 3, 4, 5]], a.split(0)
assert_equal [1, 2, 3, 4, 5], a
end end


def test_split_with_block def test_split_with_block
assert_equal [[1, 2], [4, 5], [7, 8], [10]], (1..10).to_a.split { |i| i % 3 == 0 } a = (1..10).to_a
assert_equal [[1, 2], [4, 5], [7, 8], [10]], a.split { |i| i % 3 == 0 }
assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], a
end end


def test_split_with_edge_values def test_split_with_edge_values
assert_equal [[], [2, 3, 4, 5]], [1, 2, 3, 4, 5].split(1) a = [1, 2, 3, 4, 5]
assert_equal [[1, 2, 3, 4], []], [1, 2, 3, 4, 5].split(5) assert_equal [[], [2, 3, 4, 5]], a.split(1)
assert_equal [[], [2, 3, 4], []], [1, 2, 3, 4, 5].split { |i| i == 1 || i == 5 } assert_equal [[1, 2, 3, 4], []], a.split(5)
assert_equal [[], [2, 3, 4], []], a.split { |i| i == 1 || i == 5 }
assert_equal [1, 2, 3, 4, 5], a
end end
end end


Expand Down

0 comments on commit 5b12213

Please sign in to comment.