You can't. The "listvar" method has a different scope than "one" or
"two", and thus different local variables. You could try passing a
binding to the "listvar" method, but I don't know if it's worth the
hassle.
You can't. The "listvar" method has a different scope than "one" or
"two", and thus different local variables. You could try passing a
binding to the "listvar" method, but I don't know if it's worth the
hassle.
-- Matma Rex
Thnx Matma,
It would be very convenient for me to get a list of my vars in a simple
way.
So once I'm through the hassle of writing the method ,I can use it over
and over again and enjoy!
--------
class A
聽聽def stuff
聽聽聽聽a = 4
聽聽聽聽foo = 'asd'
聽聽聽聽list_vars(binding())
聽聽end
聽聽def list_vars bnd
聽聽聽聽bnd.eval('local_variables').each{|var|
聽聽聽聽聽聽puts "#{var} is #{bnd.eval(var.to_s).class} and is equal to
#{bnd.eval(var.to_s).inspect}"
聽聽聽聽}
聽聽end
end
A.new.stuff
--------
This will print:
a is Fixnum and is equal to 4
foo is String and is equal to "asd"
The method "binding" will return a magical value that basically
contains the entire state of a script in this particular place. You
can then eval code as if it appeared in that place, and you will have
access to all variables available there.
Aside: every time you pass a block, you are also passing a binding
implicitly. So you can change this to:
class A
def stuff
a = 4
foo = 'asd'
list_vars {}
end
def list_vars &blk
bnd = blk.binding
bnd.eval('local_variables').each{|var|
val = bnd.eval(var.to_s)
puts "#{var} is #{val.class} and is equal to #{val.inspect}"
}
end
end
A.new.stuff
If you can think of something useful to do with the block, then it will
look less odd than passing an empty one