From: dblack@... Date: 2007-07-25T19:55:23+09:00 Subject: Re: Static variables in Ruby. Hi -- On Wed, 25 Jul 2007, Robert Dober wrote: > On 7/24/07, Joel VanderWerf wrote: >> Nobuyoshi Nakada wrote: >> > Hi, >> > >> > At Tue, 24 Jul 2007 17:40:57 +0900, >> > Marcin Tyman wrote in [ruby-talk:261483]: >> >> Is any way to define static variables over function? As class static >> >> variables there is possible to define a static class variable as >> >> @@name_of_var. But I'm not sure if Ruby let define such variables in >> >> functions (like in C/C++) >> > >> > def foo(x) >> > (0..0).instance_eval{x,@x = @x,x} >> > x >> > end >> > 3.times{|i|p foo(i)} #=> nil, 1, 2 >> > >> > The literal object can be Float, Regexp or Bignum, but Range >> > would be faster a bit. >> > >> >> Interesting. That is because Float, Regexp, and Bignum are instantiated >> per scope, right? >> >> Sometimes a little abstraction leakage can be useful! >> >> -- >> vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407 >> >> > I did not believe this,and why should I? > But it seems to be true ;) > def foo(x) > (0..0).instance_eval{x,@x = @x,x} > x > end > > 3.times{ |i| puts foo(i) } > (0..0).instance_eval{@x=42} > 3.times{ |i| puts foo(i) } > > Run this for a pleasant surprise :) I get the same result with or without the line between the two times calls. Are you seeing it output 42? David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)