Hi I have a string,which is been created at the run time I want to use this string as a variable to store some data into it. So how can i convert the string into variable name. Can ny one help..???
You can use eval()
for this provided that you've declared your variable first:
>> foo = []
>> eval("foo")[1] = "bar"
>> foo[1]
=> "bar"
Here are the docs.
I don't mean to be negative, but tread carefully. Ruby gives you a lot of features for highly dynamic programming such as define_method
, storing blocks as Proc
objects to be called later, etc. Generally these are cleaner code and far safer. 99% of the time using eval()
is a mistake.
And absolutely never use eval()
on a string that contains user submitted input.
If you can forgive an @ sign in front of the variable name, the following will work:
variable_name = ... # determine user-given variable name
instance_variable_set("@#{variable_name}", :something)
This will create a variable named @whatever
, with its value set to :something
. The :something
, clearly, could be anything you want. This appears to work in global scope, by declaring a spontaneous Object
instance which binds everything (I cannot find a reference for this).
The instance_variable_get
method will let you retrieve a value by name in the same manner.
instance_variable_get("@#{variable_name}")
As Jason Watkins says, a lot of people might be quick to use eval() first thing and this would be a serious mistake. Most of the time you can use the technique described by Tack if you've taken care to use a class instance variable instead of a local one.
Local variables are generally not retrievable. Anything with the @ or @@ prefix is easily retrieved.
Rather than do that directly, why not consider using a hash instead. The string would be the key, and the value you want to store would be the value. Something like this:
string_values = { }
some_string = params[:some_string] # parameter was, say "Hello"
string_values[some_string] = 42
string_values # { 'Hello' => 42 }
some_number = string_values[some_string]
some_number # 42
This has a couple of benefits. First, it means you're not doing anything magic that might be hard to figure out later. Second, you're using a very common Ruby idiom that's used for similar functionality throughout Rails.