Bird
0
0

Which of the following is the correct syntax for a for loop in Ruby to print numbers 1 to 3?

easy📝 Syntax Q3 of 15
Ruby - Loops and Iteration
Which of the following is the correct syntax for a for loop in Ruby to print numbers 1 to 3?
Afor i in 1..3 do puts i end
Bfor i in 1..3 puts i end
Cfor i in 1..3 { puts i }
Dfor (i = 1; i <= 3; i++) puts i end
Step-by-Step Solution
Solution:
  1. Step 1: Recall Ruby for loop syntax

    Ruby uses 'for variable in range do ... end' or without 'do'.
  2. Step 2: Check each option

    for i in 1..3 do puts i end uses 'do' and 'end' correctly. for i in 1..3 puts i end misses 'do'. for i in 1..3 { puts i } uses braces which is invalid. for (i = 1; i <= 3; i++) puts i end uses C-style syntax which is wrong in Ruby.
  3. Final Answer:

    for i in 1..3 do puts i end -> Option A
  4. Quick Check:

    Correct Ruby for loop syntax = for i in 1..3 do puts i end [OK]
Quick Trick: Use 'for i in range do ... end' in Ruby [OK]
Common Mistakes:
  • Using C-style for loop syntax
  • Using braces instead of do/end
  • Omitting do keyword incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes