0
0
Rubyprogramming~5 mins

For loop (rarely used in Ruby) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Afor (i = 1; i <= 5; i++) { puts i }
Bfor i in 1..5 puts i end
Cfor i = 1 to 5 do puts i end
Dfor i in range(1,5): puts i
Why might Ruby programmers prefer .each over for loops?
AFor loops are the only way to loop in Ruby
BFor loops are faster
C<code>.each</code> creates a new scope for variables and fits Ruby style better
D<code>.each</code> cannot iterate over collections
What will this code print?<br>
for x in ["a", "b", "c"]
  puts x
end
puts x
Aa b c and then 'c'
Ba b c and then error
COnly a b c
DError at the for loop
Which statement about for loops in Ruby is TRUE?
AFor loops iterate over collections using 'in'
BFor loops create a new variable scope
CFor loops are the most common looping method in Ruby
DFor loops cannot iterate over ranges
What is a range in Ruby used for in a for loop?
ATo stop the loop early
BTo define a function
CTo create a hash
DTo specify a sequence of values to loop over
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.