Bird
0
0

Find the error in this Ruby code snippet:

medium📝 Debug Q7 of 15
Ruby - Loops and Iteration
Find the error in this Ruby code snippet:

for i in 1..5 do
puts i
end
puts i
AMissing 'do' keyword in for loop
BSyntax error due to missing parentheses
CNo error; variable 'i' is accessible outside the for loop
Dputs cannot be called outside the loop
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable scope in for loops

    In Ruby, the loop variable is accessible outside the for loop.
  2. Step 2: Trace the code execution

    The loop prints 1 to 5, and then the final puts i prints 5 since i holds the last value.
  3. Step 3: Identify the correct statement

    There is no error in the code; the variable i remains accessible after the loop. Other options claim invalid syntax errors.
  4. Final Answer:

    No error; variable 'i' is accessible outside the for loop -> Option C
  5. Quick Check:

    Loop variable accessible after loop in Ruby [OK]
Quick Trick: Loop variable stays accessible after for loop in Ruby [OK]
Common Mistakes:
  • Assuming loop variable is local to loop only
  • Missing do keyword (optional)
  • Thinking puts outside loop is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes