Bird
0
0

Why do closures in Ruby capture variables by reference rather than by value?

hard📝 Conceptual Q10 of 15
Ruby - Blocks, Procs, and Lambdas
Why do closures in Ruby capture variables by reference rather than by value?
ATo reflect the latest value of variables when the closure is called
BBecause Ruby does not support variable copying
CTo prevent memory leaks
DBecause closures are immutable objects
Step-by-Step Solution
Solution:
  1. Step 1: Understand closure variable capture

    Closures capture variables by reference so they see the current value when called, not the value at creation.
  2. Step 2: Reason why this is useful

    This allows closures to reflect changes in variables made after closure creation.
  3. Final Answer:

    To reflect the latest value of variables when the closure is called -> Option A
  4. Quick Check:

    Closures capture by reference to track variable changes [OK]
Quick Trick: Closures see variable changes by referencing variables [OK]
Common Mistakes:
  • Thinking closures copy variable values at creation
  • Believing Ruby lacks variable copying
  • Confusing immutability with variable capture

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes