Bird
0
0

Which of the following Ruby code snippets correctly defines a closure using Proc.new?

easy📝 Syntax Q3 of 15
Ruby - Blocks, Procs, and Lambdas
Which of the following Ruby code snippets correctly defines a closure using Proc.new?
Aproc = Proc.new { |x| x * 2 }
Bproc = Proc.new(x) { x * 2 }
Cproc = Proc.new do x; x * 2 end
Dproc = Proc.new { x -> x * 2 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand Proc.new syntax

    Proc.new takes a block and creates a closure capturing variables.
  2. Step 2: Analyze options

    proc = Proc.new { |x| x * 2 } correctly uses Proc.new with a block and a parameter |x|. proc = Proc.new(x) { x * 2 } has incorrect syntax for parameters. proc = Proc.new do x; x * 2 end incorrectly uses semicolon and block syntax. proc = Proc.new { x -> x * 2 } uses invalid lambda syntax inside Proc.new.
  3. Final Answer:

    proc = Proc.new { |x| x * 2 } -> Option A
  4. Quick Check:

    Valid Proc syntax uses block with parameters in pipes [OK]
Quick Trick: Proc.new requires block with parameters in pipes [OK]
Common Mistakes:
  • Using parentheses incorrectly with Proc.new
  • Misplacing block parameters
  • Confusing lambda syntax with Proc.new

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes