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 <sumangurung@gmail.com>
To: ruby-talk ML <ruby-talk@ruby-lang.org>
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