From: Joshua Abbott Date: 2009-01-01T13:51:26+09:00 Subject: Re: How do I pass the name of an instance variable into an o Glenn, There may be a much better way to do this, but here's what I threw together: class SomeClass attr_accessor :a, :b def initialize @a = 'A' @b = 'B' end def print_instance_variable(variable) if instance_variables.include?("@#{variable}") puts self.send("#{variable}") else raise 'Not an instance variable.' end end end x = SomeClass.new x.print_instance_variable('a') Hope that at least points you in the right direction. -- Josh http://iammrjoshua.com 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. > > Thanks, > > Glenn -- Posted via http://www.ruby-forum.com/.