A block can read and change the variables around it. How does it find them? Step through this one and watch for getlocal_WC_1:
show_yarv("sum = 0\n[1, 2, 3].each { |i| sum += i }\nsum")Three frames: <main> at the bottom, then Array#each – a method written in C, with no YARV instructions – and on top the block, with its own local i. The block's specval slot (ep[-1]) is not a block handler but a pointer to the environment it was written in: the env of <main>, past the C frame in between. getlocal_WC_1 goes one hop along that pointer – level 1 – and reads sum there. A block remembers where it was written, not who called it. That is a closure.
And when the frame the env belongs to is gone? Here the method counter returns – but its lambda lives on:
show_yarv("def counter\n count = 0\n -> { count += 1 }\nend\n\ninc = counter\ninc.call\ninc.call")When the lambda is made, Ruby copies the env of counter from the VM stack into an object on the heap (vm_make_env_object), and points the lambda's ep there. counter leaves, its frame is popped – and when the lambda runs, its ep leads to that env "now on the heap", where count keeps counting. A Proc carries its env along, and you can look into it without calling the Proc:
make = ->(food) { -> { "Chunky eats #{food}" } }
snack = make.("bacon")
[snack.call, snack.binding.local_variables, snack.binding.local_variable_get(:food)]getlocalwalkslevelsteps along the ep chain:getlocal:77.- The env moves to the heap when a Proc or binding is made:
vm_make_env_object:1180(andvm_make_env_each:1077, which also moves the envs around it). - A block's
specvalisep[-1]:VM_ENV_DATA_INDEX_SPECVAL:1418.
secret_of(pr): it gives back the value of the variable secret that the Proc pr closed over – without calling pr (the Procs it gets would complain loudly).def secret_of(pr)
# look into the env pr carries, without calling it
end
locked = ->(secret) { -> { raise "don't call me!" } }.("bacon")
secret_of(locked)