Recall & Review
beginner
What is the basic syntax of a for loop in Ruby?
The for loop syntax in Ruby is: <br>
for variable in collection # code to execute end<br>It runs the code for each item in the collection.
Click to reveal answer
beginner
Why is the for loop rarely used in Ruby?
Ruby prefers using iterators like
.each because they are more flexible and fit Ruby's style better. For loops are less common and seen as less 'Ruby-like'.Click to reveal answer
intermediate
How does a for loop differ from an each iterator in Ruby?
A for loop uses an explicit loop variable and a collection, while
.each passes each element to a block. <br>For loops do not create a new scope for the loop variable, but .each does.Click to reveal answer
beginner
Write a for loop in Ruby that prints numbers 1 to 3.
for i in 1..3 puts i end<br>This prints:<br>1<br>2<br>3
Click to reveal answer
intermediate
What happens to the loop variable after a for loop ends in Ruby?
The loop variable remains accessible after the for loop ends because for loops do not create a new scope for the variable.
Click to reveal answer
Which of these is the correct way to write a for loop in Ruby?
✗ Incorrect
Ruby uses 'for variable in collection' syntax. Option B matches this.
Why might Ruby programmers prefer
.each over for loops?✗ Incorrect
.each is preferred because it creates a new scope and is more idiomatic Ruby.What will this code print?<br>
for x in ["a", "b", "c"] puts x end puts x
✗ Incorrect
The variable x remains accessible after the loop with the last value 'c'.
Which statement about for loops in Ruby is TRUE?
✗ Incorrect
For loops use 'for variable in collection' syntax to iterate.
What is a range in Ruby used for in a for loop?
✗ Incorrect
Ranges like 1..3 specify values from 1 to 3 to loop through.
Explain how a for loop works in Ruby and why it is less commonly used than other loops.
Think about how Ruby prefers blocks and iterators.
You got /5 concepts.
Write a simple Ruby for loop that prints each element of an array and describe what happens to the loop variable after the loop.
Remember that the loop variable stays accessible after the loop.
You got /4 concepts.