instance method in_groups_of

Ruby on Rails 3.2.22.5

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

in_groups_of(number, fill_with = nil)

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).in_groups_of(3) {|group| p group}
["1", "2", "3"]
["4", "5", "6"]
["7", nil, nil]

%w(1 2 3).in_groups_of(2, ' ') {|group| p group}
["1", "2"]
["3", " "]

%w(1 2 3).in_groups_of(2, false) {|group| p group}
["1", "2"]
["3"]

Parameters

number req
fill_with opt = nil
Source
# File activesupport/lib/active_support/core_ext/array/grouping.rb, line 19
  def in_groups_of(number, fill_with = nil)
    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([fill_with] * padding)
    end

    if block_given?
      collection.each_slice(number) { |slice| yield(slice) }
    else
      groups = []
      collection.each_slice(number) { |group| groups << group }
      groups
    end
  end

Defined in activesupport/lib/active_support/core_ext/array/grouping.rb line 19 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Array

Type at least 2 characters to search.

↑↓ navigate · open · esc close