How do I pass the name of an instance variable into an object?

G

Glenn

[Note: parts of this message were removed to make it a legal post.]

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
 
J

Joshua Abbott

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
 
G

Greg Donald

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 )
 
S

Sebastian Hungerecker

Glenn said:
Can anyone tell me how I could create a method that would allow me to add
instance variables to an object?

object.instance_variable_set:)@variable_name, "value")

HTH,
Sebastian
 
S

Suman Gurung

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
 
G

Glenn

[Note: parts of this message were removed to make it a legal post.]

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 <[email protected]>
To: ruby-talk ML <[email protected]>
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,187
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top