From: Kent Dahl Date: 2003-12-13T03:47:01+09:00 Subject: Re: Simple issue giving problems 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___)