Bird
0
0

Which Ruby code correctly uses times to build an array containing the cubes of numbers from 0 to 4?

hard📝 Application Q8 of 15
Ruby - Loops and Iteration
Which Ruby code correctly uses times to build an array containing the cubes of numbers from 0 to 4?
Aarr = 5.times.map { |i| i * 3 }
Barr = [] 5.times { |i| arr << i**3 }
Carr = [] 5.times { |i| arr.push(i * i) }
Darr = (0..4).times { |i| i**3 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    Create an array of cubes from 0 to 4.
  2. Step 2: Analyze options

    arr = [] 5.times { |i| arr << i**3 } initializes an empty array and appends i cubed for each iteration from 0 to 4.
  3. Step 3: Check other options

    arr = 5.times.map { |i| i * 3 } uses map incorrectly on times (times returns integer, not enumerable). arr = [] 5.times { |i| arr.push(i * i) } pushes squares, not cubes. arr = (0..4).times { |i| i**3 } tries to call times on a range, which is invalid.
  4. Final Answer:

    arr = [] 5.times { |i| arr << i**3 } -> Option B
  5. Quick Check:

    Use times with block and append computed values [OK]
Quick Trick: Use times with block and append results to array [OK]
Common Mistakes:
MISTAKES
  • Using times on a range (invalid)
  • Confusing map with times
  • Calculating squares instead of cubes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes