Challenge - 5 Problems
Ruby For Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple for loop
What is the output of this Ruby code using a for loop?
Ruby
for i in 1..3 puts i * 2 end
Attempts:
2 left
💡 Hint
Remember the for loop iterates over the range 1 to 3 and multiplies each by 2.
✗ Incorrect
The for loop goes through numbers 1, 2, and 3. Each number is multiplied by 2 and printed, so the output is 2, 4, and 6 each on a new line.
❓ Predict Output
intermediate2:00remaining
For loop with array iteration
What will this Ruby code print?
Ruby
arr = ['a', 'b', 'c'] for letter in arr print letter end
Attempts:
2 left
💡 Hint
The print method outputs without newlines or spaces.
✗ Incorrect
The for loop goes through each element in the array and prints it without spaces or newlines, so the output is 'abc'.
❓ Predict Output
advanced2:00remaining
For loop with break statement
What is the output of this Ruby code?
Ruby
for i in 1..5 break if i > 3 puts i end
Attempts:
2 left
💡 Hint
The break stops the loop when i is greater than 3.
✗ Incorrect
The loop iterates i from 1 to 5. For i=1,2,3: i > 3 is false, so puts i. For i=4: i > 3 is true, break before puts i. Output is 1
2
3
.
❓ Predict Output
advanced2:00remaining
For loop variable scope
What is the value of variable x after this Ruby code runs?
Ruby
x = 10 for x in 1..3 # loop body empty end puts x
Attempts:
2 left
💡 Hint
In Ruby, the for loop variable reassigns the outer variable.
✗ Incorrect
The for loop assigns x to 1, then 2, then 3. After the loop, x keeps the last value 3.
🧠 Conceptual
expert2:00remaining
Why is for loop rarely used in Ruby?
Which reason best explains why the for loop is rarely used in Ruby?
Attempts:
2 left
💡 Hint
Think about how Ruby handles variables inside loops.
✗ Incorrect
Ruby prefers iterator methods like each because they create a new variable scope, avoiding side effects on outer variables, unlike for loops which reuse the outer variable.