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

🛴ループ処理まとめ🔁❻ ー .while / .unlessメソッド

Posted at

while文とは

  • 条件式がtrueの間、ループ処理を実行する制御構文のこと
  • 条件式がfalseの間、ループ処理を実行する制御構文はunless文

記法

while 条件式 do
  処理内容
end

①条件式を評価→②trueなら条件内容を実行→③処理終了後、条件式を再評価→④falseの時点でループ終了

制御キーワード

  • break:ループ即時終了
  • next:現在のループをスキップ
  • redo:同じループを再実行

基本的な例

i = 1
while i <= 5 do
  puts i
  i += 1
end

# 実行結果 => 1 2 3 4 5

i += 1の役割

  • i += 1i = i + 1
    ⚫️ i = 1の場合
  • iは常に1のまま→ずっとtrue→無限ループ
    ⚫️ i += 1の場合
  • puts iを実行後、次のループでi + 1がなされる

breakで即時終了

i = 1
while i <= 5
  break if i == 3
  puts i
  i += 1
end

# 実行結果 => 1 2

nextで次の処理へスキップ

i = 0
while i < 0
  i += 1
  next if i == 3
  puts i
end

# 実行結果 => 1 2 4 5

まとめてみて

  • i += 1がたまに頭から抜ける。
  • redoの理解が乏しいから、学習して深めたい。
1
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
1
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?