From: Brian Candler Date: 2008-09-29T17:23:31+09:00 Subject: Re: Variable name to string reuben doetsch wrote: > I would like to get the name of the variable in string form, any way > this is > possible? > > var = 5 > puts var.foo #Want this ti put var Well, you can do this the other way round: varname = "foo" eval("#{varname} = 5") puts varname But you almost certainly *don't* want to do this. This is abuse of both local variables and eval, and it means you're solving the wrong problem, or solving the problem in the wrong way. Things you might reasonably do dynamically are: * invoke methods on an object obj = "hello" meth = "upcase" p obj.send(meth) # "HELLO" * set and read instance variables of an object obj = Object.new ivar = "@foo" obj.instance_variable_set(ivar, 5) p obj.instance_variable_get(ivar) # 5 * locate a constant or class by name klassname = "String" klass = Object.const_get(klassname) obj = klass.new p obj # "" * add methods in a module to an object module Foo def double self * 2 end end obj = "hello" obj.extend Foo p obj.double # "hellohello" * define new methods in a class or an object Leave this one until you know the language more deeply :-) -- Posted via http://www.ruby-forum.com/.