tags:

views:

96

answers:

2

Say, I've got a class definition,

class A; a = 1; end

How could get the value of 'a' outside of A?

I've tried:

eval 'p a', A.send(:binding)

failed, said:

NameError: undefined local variable or method `a' for A:Class
from (irb):2:in `send'
from (irb):2
from :0
A: 

I don't think so (without resorting to source-inspection). A binding is ultimately tied to some lexical scope: how to access it from another unless it's been stored? The example below cheats, of course.

b = class A
  x = 20
  binding
end

eval "p x", b

This may also be implementation-specific (on 1.8.7 but not 1.9, for instance). I have tried all the combinations of bindings and/or local_variables that I can think of and still no love. Of course, I could just be doing it wrong. It would be nice to see a solution.

pst
good one, the point here is to access the local variable without returning the binding
leomayleomay
A: 

With that precise definition, there is a way:

secret_val = class A; a = 1; end
puts a

Otherwise, once the class definition context goes away, that local variable disappears.

Wait. In the original quiz question you linked to in the comments, those are instance variables, not locals. That's cake. Just use instance_variable_get("@a") on the class and an instance, respectively.

Chuck
to Chuck,serect_val = class A; a = 1; endputs secret_valwill print 1 to the screen, that's correct, but how could you get the value of 'a' if it's not the last expression in the class definition?
leomayleomay
@Chuck there is 'a' in addition to @a and @@a :(
pst