1
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?

【Ruby】each_slice(n)メソッドの流れ

Posted at

each_slice(n)メソッドとは。

n 要素ずつブロックに渡して繰り返します。
要素数が n で割り切れないときは、最後の回だけ要素数が減ります。
ブロックを省略した場合は n 要素ずつ繰り返す Enumerator を返します。
https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/each_slice.html

練習

  • 標準入力
1 2 3 4 5 6 7 8 9
  • each_sliceメソッド処理
nums = gets.chomp.split(' ') 
# nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

nums.each_slice(3) do |group| 
  # each_slice(3)により配列を3要素ごとに分割。['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']
  puts group.join(' ')
  # 配列要素を半角スペースを入れて結合。"1 2 3", "4 5 6", "7 8 9"
  end
  • 出力結果
1 2 3
4 5 6
7 8 9
1
0
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
1
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?