diff options
Diffstat (limited to 'activesupport/lib/active_support')
-rw-r--r-- | activesupport/lib/active_support/core_ext/array.rb | 19 |
1 files changed, 19 insertions, 0 deletions
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 |