Bird
0
0

Which of the following Ruby code snippets correctly defines a lambda that takes one argument and doubles it?

easy📝 Syntax Q3 of 15
Ruby - Blocks, Procs, and Lambdas
Which of the following Ruby code snippets correctly defines a lambda that takes one argument and doubles it?
Adouble = lambda x { x * 2 }
Bdouble = Proc.new { |x| x * 2 }
Cdouble = ->(x) { x * 2 }
Ddouble = lambda ->(x) { x * 2 }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct lambda syntax

    In Ruby, a lambda can be created using the stabby lambda syntax: ->(args) { block }.
  2. Step 2: Evaluate each option

    double = ->(x) { x * 2 } uses the correct stabby lambda syntax.
    double = Proc.new { |x| x * 2 } creates a Proc, not a lambda.
    double = lambda x { x * 2 } is invalid syntax; lambda requires parentheses around arguments.
    double = lambda ->(x) { x * 2 } incorrectly nests lambda and stabby lambda syntax.
  3. Final Answer:

    double = ->(x) { x * 2 } -> Option C
  4. Quick Check:

    Use ->(args) { } for lambdas [OK]
Quick Trick: Use ->(args) { } for lambdas [OK]
Common Mistakes:
  • Confusing Proc.new with lambda syntax
  • Omitting parentheses around lambda arguments
  • Using invalid nested lambda syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes