Bird
0
0

You want to create a Proc that returns the square of a number and then call it for numbers 1 to 3, collecting results in an array. Which code correctly does this?

hard📝 Application Q8 of 15
Ruby - Blocks, Procs, and Lambdas
You want to create a Proc that returns the square of a number and then call it for numbers 1 to 3, collecting results in an array. Which code correctly does this?
Asquare = proc { |n| n * n } results = (1..3).map { |x| square.call(x) } puts results.inspect
Bsquare = proc { |n| n ** 2 } results = (1..3).each { |x| square.call(x) } puts results.inspect
Csquare = proc { |n| n * n } results = (1..3).map { |x| square(x) } puts results
Dsquare = proc { |n| n * n } results = (1..3).map { |x| square.call } puts results.inspect
Step-by-Step Solution
Solution:
  1. Step 1: Check Proc definition

    A valid Proc for squaring uses proc { |n| n * n } or equivalent n ** 2.
  2. Step 2: Verify collection method and call syntax

    Correct code uses (1..3).map { |x| square.call(x) } to collect [1, 4, 9]; each returns original range, missing .call or arg causes error.
  3. Step 3: Confirm output

    puts results.inspect prints [1, 4, 9].
  4. Final Answer:

    square = proc { |n| n * n } results = (1..3).map { |x| square.call(x) } puts results.inspect -> Option A
  5. Quick Check:

    Outputs [1, 4, 9] [OK]
Quick Trick: Use map with .call to collect Proc results in array [OK]
Common Mistakes:
  • Using each instead of map for collecting results
  • Calling Proc without arguments
  • Trying to call Proc like a method without .call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes