| Module | ActiveSupport::CoreExtensions::Array::Grouping |
| In: |
vendor/rails/activesupport/lib/active_support/core_ext/array/grouping.rb
|
Iterates over the array in groups of size number, padding any remaining slots with fill_with unless it is false.
%w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
["1", "2", "3"]
["4", "5", "6"]
["7", nil, nil]
%w(1 2 3).in_groups_of(2, ' ') {|g| p g}
["1", "2"]
["3", " "]
%w(1 2 3).in_groups_of(2, false) {|g| p g}
["1", "2"]
["3"]
# File vendor/rails/activesupport/lib/active_support/core_ext/array/grouping.rb, line 22
22: def in_groups_of(number, fill_with = nil, &block)
23: if fill_with == false
24: collection = self
25: else
26: # size % number gives how many extra we have;
27: # subtracting from number gives how many to add;
28: # modulo number ensures we don't add group of just fill.
29: padding = (number - size % number) % number
30: collection = dup.concat([fill_with] * padding)
31: end
32:
33: if block_given?
34: collection.each_slice(number, &block)
35: else
36: returning [] do |groups|
37: collection.each_slice(number) { |group| groups << group }
38: end
39: end
40: end
Divides the array into one or more subarrays based on a delimiting value or the result of an optional block.
[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]]
# File vendor/rails/activesupport/lib/active_support/core_ext/array/grouping.rb, line 47
47: def split(value = nil, &block)
48: block ||= Proc.new { |e| e == value }
49:
50: inject([[]]) do |results, element|
51: if block.call(element)
52: results << []
53: else
54: results.last << element
55: end
56:
57: results
58: end
59: end