From: Joshua Abbott Date: 2009-01-01T14:49:18+09:00 Subject: Re: How do I pass the name of an instance variable into an o Thanks Greg! Much nicer than what I threw together. -- Josh http://iammrjoshua.com Greg Donald wrote: > On Wed, Dec 31, 2008 at 9:18 PM, Glenn wrote: >> end >> x.print_instance_variables(:b) # writes the value of @b to the console >> x.print_instance_variables(:a, :b) # writes the values of @a and @b to the console >> x.print_instance_variables(:z) # causes an exception because there is no@z >> >> Any suggestions would be greatly appreciated. > > > class SomeClass > def initialize > @a = 1 > @b = 'xxx' > end > > def print_instance_variables( *args ) > args.each do |arg| > raise unless instance_variable_defined?( "@#{ arg }" ) > puts self.instance_variable_get( "@#{ arg }" ) > end > end > > end > > x = SomeClass.new > x.print_instance_variables( :a ) > x.print_instance_variables( :b ) > x.print_instance_variables( :a, :b ) > x.print_instance_variables( :z ) -- Posted via http://www.ruby-forum.com/.