Ruby, Procs, and Local Variables

In Ruby, procs seems to have access to local variables that were present at the time they were declared, even if they ran in a different area:

module Scope1
    def self.scope1_method
        puts "In scope1_method"
    end
end

module Scope2
    def self.get_proc
        x = 42
        Proc.new do
            puts x
            puts self
            scope1_method
        end
    end
end

Scope1.instance_eval(&Scope2.get_proc)

Conclusion:

42
Scope1
In scope1_method

How and why is this happening?

+5
source share
2 answers

The call Proc.newcreates a closure for the block it gave. When creating a closure for a block, the block is tied to the source variables in the call area Proc.new.

Why is this done?

It allows Ruby blocks to function as closures. Closing is extremely useful, and the Wikipedia entry (linked above) does a great job explaining some of their applications.

How it's done?

Ruby VM ( C), Ruby, Proc.new. . , . Ruby 1.8 proc_alloc eval.c. Ruby 1.9 proc_new proc.c.

+4

. Ruby , procs lambdas . Ruby.

+1

All Articles