From: Brian Candler Date: 2008-09-19T17:03:47+09:00 Subject: Re: variable name Rick Tan wrote: > Is there a way in Ruby to use the content of a variable as the name of a > variable. For example > > var1 = 'myVar' > > i want to assign a value to 'myVar' by referencing var1. The name of > the variable can vary depending on the content of var1. If you're talking about "myVar" being the name of a *local* variable, then usually this means you're trying to solve the wrong problem :-) The normal solution is for var1 to refer to one of the following. (1) an instance variable of an object var1 = '@foo' val = obj.instance_variable_get(var1) obj.instance_variable_set(var1, val + 1) (You can omit 'obj.' if you're talking about instance variables of the 'self' object) (2) a method name var1 = "foo" obj.send(var1, 2, 3) # same as obj.foo(2,3) var1 = "foo=" obj.send(var1, 4) # same as obj.foo = 4 (3) a constant or a class name var1 = "String" klass = Object.const_get(var1) str = klass.new # same as str = String.new require 'net/http' var1 = "HTTP" klass = Net.const_get(var1) klass.new(...) # same as Net::HTTP.new(...) > Other > application include using a variable to hold the name of a class method > which i need to call in my code. For that you use "send": MyClass.send(var1, arg, arg...) HTH, Brian. -- Posted via http://www.ruby-forum.com/.