views:

71

answers:

2
class Foo
  def initialize
    bar = 10
  end
  fiz = 5
end

Is there a possibility to get these local values (outside the class) ?

A: 

No. Once a local variable goes out of scope (for bar that is when the initialize method has run - for fiz when the end of the class definition has been reached), it's gone. No trace left.

While a local variable is still in scope you can see it (well, its name) with local_variables and get and set its value with eval (though that's definitely not recommended for sanity reasons), but once it's out of scope, that's it. No way to get it back.

sepp2k
+1  A: 

The local variable in initialize would be lost.

You are able to get the value fiz outside of the class, but only upon defining that class, and recording the return of the definition of the class.

return_of_class_definition = (class A ; fiz = 5 ; end) would assign the value of fiz to the variable.

vgoff
Note that that only works because `fiz = 5` happens to be the last expression in the class body.
sepp2k
vgoff? That's familiar. A similar technique could be used to get the value of 'bar': class SonOfFoo << Foo def initialize bar = 10 end fiz = 5end class AA < A def initialize() puts super endend
Cary Swoveland
Please disregard most of the comment I just left. (Editing problems.) To get 'bar', create a subclass of Foo containing def initialize() puts super; end.
Cary Swoveland
Exactly @sepp2k, and it feels like programming by side affect in this case, right? Not like the more accepted 'last statement evaluated' being returned in a method. But "Know the rules, so you know how to break them."
vgoff