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 3 years have passed since last update.

while

Posted at

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

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

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

while true do    
  処理するアクション
end

上記の書き方だと無限ループするので、任意のタイミングで中断させたい場合はctrl+cを押します。

**(問)**以下の仕様を満たすアプリケーションを作成します。
「仕様」:プログラムの実行すると、
①「[0]:カロリーを表示する、[1]:終了する」という選択肢が表示され、数字を入力することができる
② 0を入力すると「500kcal」と表示され、上記条件①が繰り返し実行される。
③ 1を入力するとアプリケーションが終了する

解答例

while true do
  puts "[0]:カロリーを表示する"
  puts "[1]:終了する"
  input = gets.to_i

  if input == 0
    puts "500kcal"
  elsif input == 1
    exit
  end
end
1
1
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
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?