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]繰り返し処理 times do end

0
Last updated at Posted at 2021-02-08

初めに

アウトプットさせてもらいます

繰り返し処理の使い方

例えば1から10までの数を順に足した結果を求めるプログラムを作成してみます。

sum = 0

sum = sum + 1
sum = sum + 2
sum = sum + 3
sum = sum + 4
sum = sum + 5
sum = sum + 6
sum = sum + 7
sum = sum + 8
sum = sum + 9
sum = sum + 10

puts "合計は#{sum}です"

# 実行結果
合計は55です

このように1つ1つ処理を記述していくことも可能ですが、このコードは非常に長く、かつ同じ処理が続いてるため、times文を使って効率的なコードに書き換えます。

tims文を使った場合

sum = 0
10.times do |i|
  sum = sum + i + 1
end
puts "合計は#{sum}です"

# 実行結果
合計は55です

times文では、変数iの中に繰り返しの回数が数値として自動で代入されます。よって、変数iを使えば繰り返しの回数を変数sumに足していくことができます。
ただし、プログラムなので1回目のiの数値は0となります。よってsumに足すのは1増やしたi + 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?