mirror of
https://github.com/github/rails.git
synced 2026-02-06 04:05:17 -05:00
Add Array#split for dividing arrays into one or more subarrays by value or block
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4208 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
@@ -1,3 +1,7 @@
|
||||
*SVN*
|
||||
|
||||
* Add Array#split for dividing arrays into one or more subarrays by value or block. [Sam Stephenson]
|
||||
|
||||
*1.3.1* (April 6th, 2005)
|
||||
|
||||
* Clean paths inside of exception messages and traces. [Nicholas Seckar]
|
||||
|
||||
@@ -18,4 +18,23 @@ class Array #:nodoc:
|
||||
collection << fill_with until collection.size.modulo(number).zero?
|
||||
collection.each_slice(number, &block)
|
||||
end
|
||||
|
||||
# Divide the array into one or more subarrays based on a delimiting +value+
|
||||
# or the result of an optional block.
|
||||
#
|
||||
# ex.
|
||||
#
|
||||
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
|
||||
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
|
||||
def split(value = nil, &block)
|
||||
block ||= Proc.new { |e| e == value }
|
||||
inject([[]]) do |results, element|
|
||||
if block.call(element)
|
||||
results << []
|
||||
else
|
||||
results.last << element
|
||||
end
|
||||
results
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -69,7 +69,28 @@ class ArrayExtGroupingTests < Test::Unit::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
class ArraToXmlTests < Test::Unit::TestCase
|
||||
class ArraySplitTests < Test::Unit::TestCase
|
||||
def test_split_with_empty_array
|
||||
assert_equal [[]], [].split(0)
|
||||
end
|
||||
|
||||
def test_split_with_argument
|
||||
assert_equal [[1, 2], [4, 5]], [1, 2, 3, 4, 5].split(3)
|
||||
assert_equal [[1, 2, 3, 4, 5]], [1, 2, 3, 4, 5].split(0)
|
||||
end
|
||||
|
||||
def test_split_with_block
|
||||
assert_equal [[1, 2], [4, 5], [7, 8], [10]], (1..10).to_a.split { |i| i % 3 == 0 }
|
||||
end
|
||||
|
||||
def test_split_with_edge_values
|
||||
assert_equal [[], [2, 3, 4, 5]], [1, 2, 3, 4, 5].split(1)
|
||||
assert_equal [[1, 2, 3, 4], []], [1, 2, 3, 4, 5].split(5)
|
||||
assert_equal [[], [2, 3, 4], []], [1, 2, 3, 4, 5].split { |i| i == 1 || i == 5 }
|
||||
end
|
||||
end
|
||||
|
||||
class ArrayToXmlTests < Test::Unit::TestCase
|
||||
def test_to_xml
|
||||
xml = [
|
||||
{ :name => "David", :age => 26 }, { :name => "Jason", :age => 31 }
|
||||
|
||||
Reference in New Issue
Block a user