From: Michael Winterstein Date: 2009-11-29T03:15:24+09:00 Subject: Re: Local variables can't be accessed from outside, right? Benoit Daloze wrote: > > 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? > No, it's just an example for learning about metaprogramming. Which is why it seems strange; the local variables can only be 'accessed' because they happen to be return values. I did learn something I didn't know, however : class A puts "Local variables: #{local_variables}" puts "Instance variables: #{instance_variables}" a = 5 @a = 6 puts "Local variables: #{local_variables}" puts "Instance variables: #{instance_variables}" end Local variables: a Instance variables: Local variables: a Instance variables: @a So local variables exist in some ethereal void after the code is scanned but before they can be used; not so with instance variables. That makes some sense. But this also lets you do this eval weirdness. class B puts "#{local_variables.first} = #{eval(local_variables.first)}, which is a #{eval(local_variables.first).class}" eval(local_variables.first + "=2") puts "#{local_variables.first} = #{eval(local_variables.first)}, which is a #{eval(local_variables.first).class}" puts #{a} if a #=> NameError: undefined local variable or method 'a' for B:Class a = 4 puts "#{local_variables.first} = #{eval(local_variables.first)}, which is a #{eval(local_variables.first).class}" end With the error commented out, this gives: a = , which is a NilClass a = 2, which is a Fixnum a = 4, which is a Fixnum -- Posted via http://www.ruby-forum.com/.