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?

🛴ループ処理まとめ🔁❸ ー .timesメソッド

Posted at

Ruby の反復処理でよく使う「整数限定」の繰り返し方法、.times メソッドについて、アウトプットします。
返り値や each との違いも整理して、サンプルコードとともに見ていきたいと思います。


.times メソッドとは

  • Integer クラスに定義されているメソッドで、整数(レシーバーの値)回だけ繰り返し処理を実行する
  • 戻り値はレシーバー(メソッドを呼んだ整数そのもの)

基本的な書き方

複数行ブロック

n.times do |i|
  # i を使った処理
end

単一行ブロック

n.times { |i| 処理 }
  • ブロック引数 i には 0 から n-1 までの整数が順に渡る

  • メソッドの戻り値はレシーバーの整数 n

3.times do |i|
  puts i
end

# 出力
# 0
# 1
# 2

# 戻り値
=> 3

.each メソッドとの違い

項目 .each .times
対象 Enumerable(Array、Range など) Integer
繰り返す回数 Collection の要素数分 レシーバーの値分
ブロック引数に渡される値 各要素 0 〜 n-1 の整数
返り値 元の Enumerable オブジェクト レシーバーの整数
ブロック省略時の返り値 Enumerator Enumerator
主な用途 配列や範囲の各要素を順に処理する 同じ処理を指定回数だけ繰り返す
# .times を使った例
4.times do |i|
  puts i
end
# => 0, 1, 2, 3
#    戻り値: 4

# (0..3).each を使った例
(0..3).each do |j|
  puts j
end
# => 0, 1, 2, 3
#    戻り値: (0..3)
  • .each は Array や Range など「要素を持つオブジェクト」の反復に

  • .times は「整数を上限にした同一処理の繰り返し」に

  • とはいえ、(0..n-1).each で整数回の繰り返しも可能です


まとめてみて

  • n.times do |i| で回すよりも、(1..n).each do |i| の方が自分としては見やすいから多用したい。
  • n.times : 0からn-1まで繰り返す
  • (1..n).each : 1からnまで繰り返す 👈包括的範囲
  • (1...n).each : 1からn-1まで繰り返す 👈排他的範囲
0
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
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?