A deep dive into how Ruby's YARV virtual machine implements closures under the hood. When a lambda or proc captures a local variable, Ruby copies the current stack frame environment to the heap, creating an rb_env_t object. Crucially, Ruby then redirects the Environment Pointer (EP) to the heap copy, so all subsequent variable accesses — including mutations — go through the heap. This explains why multiple lambdas in the same scope share the same captured variables (they reuse the same rb_env_t), why variable modifications after lambda creation are visible inside the closure, and why local variables survive after their enclosing method returns. Internally, both lambda and Proc.new produce an rb_proc_t object distinguished only by an is_lambda boolean flag.

4m read timeFrom rubystacknews.com
Post cover image
Table of contents
Why does a local variable survive after a method returns?A normal method calllambda changes everythingThe hidden trick: Ruby rewrites the Environment PointerWhy multiple lambdas share variablesThe Proc object is the closureWhy this mattersFinal ThoughtsShare this:Related
183 Impressions