instance method
in_groups_of
Ruby on Rails edge
Since v3.0.20Signature
in_groups_of(number, fill_with = nil, &block)
Splits or 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 8 9 10).in_groups_of(3) {|group| p group}
["1", "2", "3"]
["4", "5", "6"]
["7", "8", "9"]
["10", nil, nil]
%w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group}
["1", "2"]
["3", "4"]
["5", " "]
%w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
["1", "2"]
["3", "4"]
["5"]
```
: (Integer, ?nil) -> Array[Array] : (Integer, ?nil) { (Array) -> void } -> Array : (Integer, false) -> Array[Array] : (Integer, false) { (Array) -> void } -> Array : [FillType] (Integer, FillType) -> Array[Array[Elem | FillType]] : [FillType] (Integer, FillType) { (Array[Elem | FillType]) -> void } -> Array[Elem | FillType]
Parameters
-
numberreq -
fill_withopt = nil -
blockblock
Source
# File activesupport/lib/active_support/core_ext/array/grouping.rb, line 30
def in_groups_of(number, fill_with = nil, &block)
if number.to_i <= 0
raise ArgumentError,
"Group size must be a positive integer, was #{number.inspect}"
end
if fill_with == false
collection = self
else
# size % number gives how many extra we have;
# subtracting from number gives how many to add;
# modulo number ensures we don't add group of just fill.
padding = (number - size % number) % number
collection = dup.concat(Array.new(padding, fill_with))
end
if block_given?
collection.each_slice(number, &block)
else
collection.each_slice(number).to_a
end
end
Defined in activesupport/lib/active_support/core_ext/array/grouping.rb line 30
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Array