Help with closure contexts

Question: Could you please explain to me why the context is copied
in the first case and not in the second ?

=> code

copy of the context for a closure

def nTimes(aThing)
return proc { |n| aThing * n }
end

a = 23
p1 = nTimes(a)
puts p1.call(3)
a = 2
puts p1.call(4)

versus reference to the context

class TestMe
attr_reader :myProc
def initialize()
@myProc = proc { puts @a }
@a = 0
end
def changeMember()
@a = 2
end
end

testMeFirst = TestMe.new
testMeFirst.myProc.call
testMeFirst.changeMember
testMeFirst.myProc.call

<= code

results in:

[bla@blub myTests]$ ruby test1.ruby
69
92
0
2

Question: Could you please explain to me why the context is copied
in the first case and not in the second ?

In the first you make reference to a local variable.

In the second to an instance variable : an instance variable is associated
with an object, not a context.

Guy Decoux

Hello t_gecks,

Monday, November 11, 2002, 5:25:50 PM, you wrote:

Question: Could you please explain to me why the context is copied
in the first case and not in the second ?

because variables holds only references to values. after you execute
“a=2” statement, aThing is not changed - it got it’s value, reference
to 23 at the time of call. Try to reexecute “p1=nTimes(a)” after that
to get closure with new aThing

In the second example references to @a yields actual value of instance
variable. btw, try this code:

def nTimes(aThing)
return proc { |n| aThing * n }
end

a = “23”
p1 = nTimes(a)
puts p1.call(3)
a << “4”
puts p1.call(4)

:)))

=>> code

···

copy of the context for a closure

def nTimes(aThing)
return proc { |n| aThing * n }
end

a = 23
p1 = nTimes(a)
puts p1.call(3)
a = 2
puts p1.call(4)

versus reference to the context

class TestMe
attr_reader :myProc
def initialize()
@myProc = proc { puts @a }
@a = 0
end
def changeMember()
@a = 2
end
end

testMeFirst = TestMe.new
testMeFirst.myProc.call
testMeFirst.changeMember
testMeFirst.myProc.call

<= code

results in:

[bla@blub myTests]$ ruby test1.ruby
69
92
0
2


Best regards,
Bulat mailto:bulatz@integ.ru