Bird
0
0

You want to create an array of squares of numbers from 1 to 5 using upto. Which code correctly does this?

hard📝 Application Q8 of 15
Ruby - Loops and Iteration
You want to create an array of squares of numbers from 1 to 5 using upto. Which code correctly does this?
Asquares = [] 5.downto(1) { |i| squares << i * i } puts squares.join(",")
Bsquares = [] 1.upto(5) { |i| squares << i * i } puts squares.join(",")
Csquares = [] 1.downto(5) { |i| squares << i * i } puts squares.join(",")
Dsquares = [] 5.upto(1) { |i| squares << i * i } puts squares.join(",")
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct counting method

    To count from 1 to 5, use upto starting at 1.
  2. Step 2: Check code correctness

    squares = [] 1.upto(5) { |i| squares << i * i } puts squares.join(",") uses 1.upto(5) and appends squares correctly.
  3. Final Answer:

    squares = [] 1.upto(5) { |i| squares << i * i } puts squares.join(",") -> Option B
  4. Quick Check:

    Use upto for ascending range = A [OK]
Quick Trick: Use upto with block to build arrays ascending [OK]
Common Mistakes:
  • Using downto to count up
  • Reversing start and end
  • Appending wrong values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes