From: Benoit Daloze Date: 2009-11-28T20:07:30+09:00 Subject: Re: Local variables can't be accessed from outside, right? --001636416597e250d704796c6941 Content-Type: text/plain; charset=ISO-8859-1 class_local_a = class A def initialize @a = 11 @@a = 22 a = 33 end @a = 1 @@a = 2 a = 3 end p A.instance_variable_get(:@a) #ok p A.class_variable_get(:@@a) if RUBY_VERSION > '1.9' class A; p @@a end if RUBY_VERSION < '1.9' # a little tricky, sure p class_local_a p A.new.instance_variable_get(:@a) p A.class_variable_get(:@@a) if RUBY_VERSION > '1.9' class A; p @@a end if RUBY_VERSION < '1.9' p A.new.method(:initialize).call I didn't find other way to get the result of class A ... end like a if or case result. Very weared a class' instance variable(1) Does it have any interest? 2009/11/28 David Masover > On Friday 27 November 2009 11:56:43 pm Michael Winterstein wrote: > > Hi, I've been trying to figure out metaprogramming and I've mostly got > > it figured out, but in doing so I ran across this example: > > > > class A > > def initialize > > @a = 11 > > @@a = 22 > > a = 33 > > end > > @a = 1 > > @@a = 2 > > a = 3 > > end > > > > > > This was given as a posed question (can you access all the variables) > > and a particular order of the output was given (specifically, 1 2 3 11 > > 22 33). > > > I think a trick like puts A.new would be a lame solution, > > That actually wouldn't work, though I can see why you think it'd be lame. > > Anyway, as far as I know, there are only a few ways to access a local > variable: > > You could define a= -- for example, > > def a=(value) > puts a > end > > The problem is, I can't actually get this to work reliably. It really seems > like assignment of this kind would only work if you did > > self.a = 33 > > So, with that discarded, I don't think it's possible to get access to these > local variables with the class as written, at least not cleanly. You could > probably figure out (programatically) where the class is defined, and then > parse the source. > > Other than that, the only way I know of getting at local variables is > through > the binding object, which you'd have to get either from inside the code, or > from something called from that code -- but that class doesn't seem to call > any methods from anywhere you care about, so that doesn't work. > > --001636416597e250d704796c6941--