Bird
0
0

Which of the following is the correct way to create a closure using a lambda in Ruby?

easy📝 Syntax Q12 of 15
Ruby - Blocks, Procs, and Lambdas
Which of the following is the correct way to create a closure using a lambda in Ruby?
Aclosure = lambda { |x| x * 2 }
Bclosure = def(x) x * 2 end
Cclosure = function(x) { x * 2 }
Dclosure = -> x x * 2
Step-by-Step Solution
Solution:
  1. Step 1: Identify Ruby lambda syntax

    In Ruby, lambdas can be created with lambda { |args| ... } or ->(args) { ... }.
  2. Step 2: Check each option

    closure = lambda { |x| x * 2 } uses lambda { |x| x * 2 }, which is valid. closure = def(x) x * 2 end uses invalid syntax for a lambda. closure = function(x) { x * 2 } uses JavaScript-like syntax. closure = -> x x * 2 misses parentheses in the arrow syntax, which is invalid.
  3. Final Answer:

    closure = lambda { |x| x * 2 } -> Option A
  4. Quick Check:

    Correct lambda syntax = closure = lambda { |x| x * 2 } [OK]
Quick Trick: Use lambda { |args| ... } for Ruby closures [OK]
Common Mistakes:
  • Using JavaScript or Python syntax
  • Omitting parentheses in arrow lambdas
  • Trying to define lambdas with def keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes