Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

ActiveSupport | Array#in_groups

概要

Array#in_groups

詳細

Array#in_groups について

Array#in_groups

引数で指定した要素数の配列に分割します。

サンプル

# encoding: utf-8
require 'active_support/core_ext/array/grouping'
require 'tbpgr_utils'

I18n.enforce_available_locales = true
ary = [*1..10]
bulk_puts_eval binding, <<-EOS
ary.in_groups 1
ary.in_groups 2
ary.in_groups 3
EOS

ary.in_groups(3) do |g|
  puts "#{g}"
end

__END__
・下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

ary.in_groups 1 # => [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
ary.in_groups 2 # => [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
ary.in_groups 3 # => [[1, 2, 3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]
[1, 2, 3, 4]
[5, 6, 7, nil]
[8, 9, 10, nil]