From c71607e29c4ab5cd7b4ac7d3ef902868ab1cebf7 Mon Sep 17 00:00:00 2001 From: Sam Stephenson Date: Thu, 13 Apr 2006 05:12:43 +0000 Subject: 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 --- activesupport/lib/active_support/core_ext/array.rb | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'activesupport/lib/active_support/core_ext/array.rb') diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb index 897d73866c..db6f5587da 100644 --- a/activesupport/lib/active_support/core_ext/array.rb +++ b/activesupport/lib/active_support/core_ext/array.rb @@ -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 -- cgit v1.2.3