Variable Method Name


#1

Hello List!

I come to you after a long while of troubleshooting and researching to
no avail. My wish is to reference a class variable whose name is
stored as a string in another variable. I will try to set up an
example:

variable_name = ‘text’
print @#{variable_name}

I think that is how it would work, and i think the syntax is nearly
correct, but… its not.

Any help? Thanks alot guys!

–nathan


#2

Any help? Thanks alot guys!

Not quite the same, but let’s say you have an AR model named Foo that
has
an attribute named bar, then:

myfoo = Foo.find(:first)
myfoo.send(‘bar’) # same as myfoo.bar

Maybe that will get you closer…


#3

On 1/12/07, BlackNute removed_email_address@domain.invalid wrote:

variable_name = ‘text’
print @#{variable_name}

instance_variable_get("@#{variable_name")

http://ruby-doc.org/core/


Chris W.
http://errtheblog.com


#4

On 1/17/07, Chris W. removed_email_address@domain.invalid wrote:

On 1/12/07, BlackNute removed_email_address@domain.invalid wrote:

variable_name = ‘text’
print @#{variable_name}

instance_variable_get("@#{variable_name")

Whoops, should be

instance_variable_get("@#{variable_name}")

of course.


#5

BlackNute wrote:

Hello List!

I come to you after a long while of troubleshooting and researching to
no avail. My wish is to reference a class variable whose name is
stored as a string in another variable. I will try to set up an
example:

variable_name = ‘text’
print @#{variable_name}

I had asked questions like this.
http://www.ruby-forum.com/topic/93236#187853
http://www.ruby-forum.com/topic/93682#189535


#6

variable_name = ‘text’
print @#{variable_name}

eval(“print #{variable_name}”)


Nedforce Informatica Specialisten B.V.
http://www.nedforce.nl
+31 (0)53 4500225