From: Greg Donald Date: 2009-01-01T13:58:11+09:00 Subject: Re: How do I pass the name of an instance variable into an object? On Wed, Dec 31, 2008 at 9:18 PM, Glenn wrote: > Hi, > > Suppose I wanted to create a method for an object that allowed me to pass in the name of an instance variable and to perform some task on the variable. For the sake of simplicity, let's say that I'd like to be able to print out the value of the specified instance variable. Also, I'd want the method to raise an exception if the name of the variable getting passed into the object is not actually an instance variable in the object. > > The class would look something like this: > > class SomeClass > def initialize > @a = 1 > @b = 'xxx' > end > > def print_instance_variables(obj) > # some code goes here > end > end > > And here's how I'd like to be able to use it: > > x = SomeClass.new > x.print_instance_variables(:a) # writes the value of @a to the console > 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 ) -- Greg Donald http://destiney.com/