0
0
Rubyprogramming~5 mins

Closures and variable binding in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a closure in Ruby?
A closure is a block, proc, or lambda that captures variables from its surrounding context, allowing it to access those variables even when executed outside that context.
Click to reveal answer
intermediate
How does variable binding work inside a Ruby closure?
Variables used inside a closure capture the variables from the surrounding scope by reference, so the closure sees their updated values even if the variables change later.
Click to reveal answer
intermediate
What is the difference between a Proc and a lambda in Ruby closures?
Both are closures, but lambdas check the number of arguments and return control to the calling method, while Procs are more lenient with arguments and return from the enclosing context.
Click to reveal answer
advanced
Explain with an example how a closure can remember a variable's value after the variable changes.
Example: <br> x = 10<br> closure = -> { x }<br> x = 20<br> closure.call # returns 20 because closure captures variable by reference, not by value.
Click to reveal answer
beginner
Why are closures useful in Ruby programming?
Closures let you write flexible code by capturing context, enabling callbacks, delayed execution, and maintaining state without global variables.
Click to reveal answer
What does a Ruby closure capture from its surrounding environment?
AOnly global variables
BVariables and their current values
COnly method names
DNothing, closures have no context
In Ruby, what happens if you change a variable after creating a closure that uses it?
AThe closure breaks and raises an error
BThe closure keeps the old value forever
CThe closure sees the updated variable value
DThe closure ignores the variable
Which Ruby closure type checks the number of arguments strictly?
ALambda
BProc
CBlock
DMethod
What is a common use case for closures in Ruby?
ATo create global variables
BTo perform file I/O
CTo define classes
DTo delay execution and maintain state
Which of these is NOT a closure in Ruby?
AClass
BProc
CLambda
DBlock
Explain what a closure is in Ruby and how it handles variable binding.
Think about how blocks or lambdas remember variables from outside.
You got /4 concepts.
    Describe the difference between a Proc and a lambda in Ruby closures.
    Focus on argument checking and return behavior.
    You got /4 concepts.