1
1

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.

While の基本

Last updated at Posted at 2020-04-06

環境,前提

Ruby 2.5.1
MacOS Mojave Ver.10.14.6

本記事はRubyがインストールされた前提の記事です。
Rubyをインストールしたあと、とにかくRubyをいろいろ触ってみて慣れていくための記事です。お役に立てば幸いです。

whileの基本

sample.rb
while 条件 do
   // 繰り返す処理
end

では1から10までの合計をwhileを用いて算出してみます。

sample.rb
sum = 0
i = 1
while i <= 10 do
sum += i
i+=1
end
puts sum

実行結果は以下のように55となります。

Tarminal
55

whileとforの使い分け

どちらも繰り返し処理の際に用いられるものですが、どういった使い分けが良いでしょうか?以下のように使い分けるのが良いと思います。

・繰り返し回数が決まっておらず、条件を満たす限り回すのはwhile
・回数が明確に決まっている場合はfor

1
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?