136
95

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.

ある配列を任意の要素数の配列に分割したい

Last updated at Posted at 2014-01-17

概要

ある配列を任意の長さ n ずつ分解したいです。
例えば、
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]] にしたいということです。

簡単にできるんです。そう Enumerable#each_slice ならね。

array = (0..10).to_a
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

array.each_slice(3).to_a
#=> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]

Enumerable#each_slice メソッドは Enumerator オブジェクトを返すので、
to_a で Array に変換して完成です :tada:

追記

Active Support コア拡張機能Array#in_groups_of でも同様のことができました。

$ gem install activesupport
require 'active_support/core_ext/array/grouping'

array = (0..10).to_a
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 第 1 引数のみの場合、余りが nil で埋められる。
array.in_groups_of(3)
#=> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, nil]]

# 第 2 引数に false を指定した場合、
# 前述の Enumerable#each_slice を使用した方法と同じ結果になる。
array.in_groups_of(3, false)
#=> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
136
95
2

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
136
95

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?