0
0
Rubyprogramming~5 mins

While loop in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a while loop in Ruby?
A while loop repeats a block of code as long as a given condition is true. It checks the condition before each repetition.
Click to reveal answer
beginner
How do you write a simple while loop in Ruby that counts from 1 to 5?
You can write:<br>
i = 1
while i <= 5
  puts i
  i += 1
end
<br>This prints numbers 1 to 5.
Click to reveal answer
intermediate
What happens if the condition in a while loop is never false?
The loop runs forever, causing an infinite loop. This can freeze your program unless you stop it manually.
Click to reveal answer
beginner
Can you use a while loop with a condition that changes inside the loop? Give an example.
Yes. For example:<br>
count = 3
while count > 0
  puts count
  count -= 1
end
<br>The condition changes as count decreases.
Click to reveal answer
intermediate
What is the difference between a while loop and an until loop in Ruby?
A while loop runs while the condition is true.<br>An until loop runs until the condition becomes true (runs while condition is false).
Click to reveal answer
What does a while loop do in Ruby?
ARepeats code while a condition is true
BRepeats code once regardless of condition
CRuns code only if condition is false
DStops code execution immediately
What will this code print?<br>
i = 1
while i < 3
  puts i
  i += 1
end
A1 2
B1 2 3
C2 3
D3
What happens if the condition in a while loop is false at the start?
AThe loop runs forever
BThe loop does not run at all
CThe loop runs once
DThe loop runs twice
Which of these can cause an infinite while loop?
AIncrementing a variable inside the loop
BCondition is false initially
CCondition never becomes false
DUsing break inside the loop
How do you stop a while loop early in Ruby?
AUse the exit keyword
BUse the stop keyword
CUse the continue keyword
DUse the break keyword
Explain how a while loop works in Ruby and give a simple example.
Think about counting numbers using a variable.
You got /3 concepts.
    What are the risks of using a while loop and how can you avoid them?
    Consider what happens if the condition never changes.
    You got /3 concepts.