Bird
0
0

How can you create a Proc that accepts any number of arguments and returns their sum?

hard📝 Application Q9 of 15
Ruby - Blocks, Procs, and Lambdas
How can you create a Proc that accepts any number of arguments and returns their sum?
Asum_proc = proc { args.sum }
Bsum_proc = proc { |args| args.sum }
Csum_proc = proc { |*args| args.sum }
Dsum_proc = proc { |args| args.reduce(:+) }
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to accept variable arguments

    Using |*args| allows the Proc to accept any number of arguments as an array.
  2. Step 2: Sum the arguments

    Calling args.sum returns the sum of all arguments.
  3. Step 3: Check each option

    Only sum_proc = proc { |*args| args.sum } correctly uses |*args| to accept multiple arguments and sums them.
  4. Final Answer:

    sum_proc = proc { |*args| args.sum } -> Option C
  5. Quick Check:

    Proc with splat args sums correctly = sum_proc = proc { |*args| args.sum } [OK]
Quick Trick: Use *args to accept any number of arguments in Proc [OK]
Common Mistakes:
  • Missing * to accept multiple arguments
  • Trying to sum without collecting arguments
  • Using wrong block parameter syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes