VOOZH about

URL: https://qiita.com/namitop/items/82836a938e3c9dac090f

⇱ [rails]一次元配列を分割する #Ruby - Qiita


👁 Image
3

Go to list of users who liked

2

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 5 years have passed since last update.

@namitopin👁 Image
freeeサイン株式会社

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

3
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

Go to list of users who liked

2
0

Go to list of comments

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

Go to list of users who liked

2