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