0
0

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.

配列を一定の要素数で分ける処理 Ruby編

0
Posted at
file.rb
# 今回説明に使う配列
# 要素数51
array = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
  20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
  40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
]

# 新しい配列を格納するのに使う配列
new_array = Array.new

# 古い配列を分割するサイズ
num = 10

while array.size() != 0 do
  new_array << array.shift(num)
end

print new_array

while文で行なっている処理

  1. ローカル変数arrayの要素数が1つ以上あるかを判断。1つ以上あればwhile文のブロックを実行
  2. arrayの先頭から10要素分を取り出し、新しい配列に追加

最後に新しい配列を出力

実行結果

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50]]
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?