Bird
0
0

You want to create an array of squares of numbers from 0 to 4 using times. Which code correctly does this?

hard📝 Application Q15 of 15
Ruby - Loops and Iteration
You want to create an array of squares of numbers from 0 to 4 using times. Which code correctly does this?
Asquares = (0..4).times { |i| i * i } puts squares
Bsquares = 5.times { |i| i * i } puts squares
Csquares = [] 5.times do i squares.push(i * i) end puts squares
Dsquares = [] 5.times { |i| squares << i * i } puts squares
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to collect results in an array

    Since times returns the integer, not an array, we must create an empty array and push results inside the block.
  2. Step 2: Check each option for correct syntax and logic

    squares = [] 5.times { |i| squares << i * i } puts squares initializes an empty array, uses 5.times with block parameter i, and appends i*i to the array correctly.
  3. Final Answer:

    squares = [] 5.times { |i| squares << i * i } puts squares -> Option D
  4. Quick Check:

    Use array and push inside times block [OK]
Quick Trick: Create array first, then push inside times block [OK]
Common Mistakes:
MISTAKES
  • Assuming times returns an array
  • Using invalid range with times
  • Omitting block parameter pipes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes