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.

繰り返し処理の基礎

0
Last updated at Posted at 2021-05-21

次の仕様を満たすアプリケーションを作成。

仕様

①「[0]:カロリーを表示する、[1]:終了する」という選択肢が表示され、数字を入力することができる
② 0を入力すると「500kcal」と表示され、上記条件①が繰り返し実行される。
③ 1を入力するとアプリケーションが終了する

while

条件によって繰り返し処理を行う場合はwhileを使用。
以下のように使用します。

while 条件式 do
  処理するアクション
end

もしプログラムを終了させず同じ処理を繰り返すループ処理を行う場合は、以下のようにします。

while true do    
  処理するアクション
end
実装コード
while true do
  puts "[0]:カロリーを表示する"
  puts "[1]:終了する"
  input = gets.to_i

  if input == 0
    puts "500kcal"
  elsif input == 1
    exit
  end
end

while true doとすることでdo以下の処理を繰り返します。4行目で値を入力します。その結果が、0の場合は500kcalを表示し、1を入力した場合はexitによりRubyプログラムの実行を即座に終了できます。

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