gabriele renzi wrote:
on a sidenote, Iāve been playing with:
def swapper(obj,a,b)
obj.instance_eval(ā#{a},#{b}=#{b},#{a}ā)
end
swapper(self,:a,:b)
but this doesānt work.
Because the scope of the variables is different, I believe. The method
does not have access to local variables of the calling method. Even if
you use instance_eval, you will just have access to instance variables
of the given self, not local variables for any arbitrary local method
called on it further up the callchain.
Anyway, if I do this:
p a
p b
self.instance_eval(ā#{:a},#{:b}=#{:b},#{:a}ā)
p a
p b
it works as expected (i.e. swaps the variables)
Some hints to explain me this ?
a = 3
b = 5
Will not work, different scopes.
def swapper(obj,a,b)
obj.instance_eval(ā#{a},#{b}=#{b},#{a}ā)
end
swapper(self,:a,:b)
print a, b, ā\nā #=> 35
Pass scope deliberately as a Proc.
def swapper2(a,b,&block)
eval(ā#{a},#{b}=#{b},#{a}ā, block)
end
swapper2(:a,:b){}
print a, b, ā\nā #=> 53
You can do a lot of fancy (but ugly) things with the latter form. I tend
to rewrite it to pass arguments through the Proc, just to make it look
as ugly as it really is.
Pass scope deliberately as a Proc.
def swapper3(&block)
a,b = block.call
eval(ā#{a},#{b}=#{b},#{a}ā, block)
end
swapper3{[:a,:b]}
print a, b, ā\nā #=> 35
HTH
Ā·Ā·Ā·
ā
([ Kent Dahl ]/)_ ~ [ http://www.pvv.org/~kentda/ ]/~
))_student_/(( _d L b_/ Master of Science in Technology )
( __Ƶ|Ƶ// ) )Industrial economics and technological management(
_/ƶ____/ (_engineering.discipline=Computer::Technology)