3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[rails]一次元配列を分割する

Posted at

in_groups_of

一次元配列を引数の数ずつ分割できます。
デフォルトでは要素に不足がある場合はnilが入ります。

[1,2,3,4,5].in_groups_of(2) # => [[1, 2], [3, 4], [5, nil]]

第二引数に指定することで不足分にnil以外を入れるようにできますし、
falseを指定すれば何も入れないという指定もできます。

[1,2,3,4,5].in_groups_of(2, 0) # => [[1, 2], [3, 4], [5, 0]]
[1,2,3,4,5].in_groups_of(2, false) # => [[1, 2], [3, 4], [5]]

in_groups

一次元配列を引数の数で分割できます。
デフォルトでは要素に不足がある場合はnilが入ります。

[1,2,3,4,5].in_groups(2) # => [[1, 2, 3], [4, 5, nil]]

in_groups_ofと同じく、
第二引数に指定することで不足分にnil以外を入れるようにできますし、
falseを指定すれば何も入れないという指定もできます。

[1,2,3,4,5].in_groups(2, 0) # => [[1, 2, 3], [4, 5, 0]]
[1,2,3,4,5].in_groups(2, false) # => [[1, 2, 3], [4, 5]]
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?