From: Glenn Date: 2009-01-02T03:48:49+09:00 Subject: Re: How do I pass the name of an instance variable into an object? --0-2071907309-1230835774=:48808 Content-Type: text/plain; charset=us-ascii Excellent! Thanks so much for your help. I noticed that the class of the variable always seems to be String when I use add_instance_variable. When I use instance_variable_set, though it seems to preserve the class of the object in thee 2nd parameter. In this case, x is a Fixnum: s = SomeClass.new s.instance_variable_set('@x', 22) In this case, though, x is a String: s = SomeClass.new s.add_instance_variable(:x, 22) I think that this is because of the quotes around initial_value in this line: self.instance_variable_set("@#{name}", "#{initial_value}") When I rewrote the line as: self.instance_variable_set("@#{name}", initial_value ) It maintains the original class of that 2nd parameter. Do you think that there is any harm in leaving those quotes off? Glenn ________________________________ From: Suman Gurung To: ruby-talk ML Sent: Thursday, January 1, 2009 12:46:51 PM Subject: Re: How do I pass the name of an instance variable into an object? i just tried putting everything together and it worked great. I thought i will share the consolidated code, so here it is: class SomeClass def initialize @first = 'first variable' @second = 'second variable' end def print_instance_variable(*args) args.each do |arg| begin raise unless instance_variable_defined?("@#{arg}") puts self.instance_variable_get("@#{arg}") rescue => ex puts "#{ex.class}: #{ex.message}" end end end def add_instance_variable(name, initial_value) raise if instance_variable_defined?("@#{name}") self.instance_variable_set("@#{name}", "#{initial_value}") end end x = SomeClass.new x.print_instance_variable(:first) x.print_instance_variable(:second) puts "\n****************** printing both values in one method call *************" x.print_instance_variable :first, :second puts "\n*************** should throw an exception, because the instance variable is undefined **************" x.print_instance_variable :third x.add_instance_variable(:third, "third value") puts "\n*************** should print the third instance variable**************" x.print_instance_variable :third --0-2071907309-1230835774=:48808--