From: dblack@... Date: 2006-09-10T23:19:48+09:00 Subject: Re: patching strings together to make a variable Hi -- On Sun, 10 Sep 2006, Sy Ali wrote: > I'm curious to know if I can patch multiple things together to make a > variable. > > I have some imaginary code snippets. The most direct way I can think > of is something like this: > > $a = true > $var = "fail" > $variable = "pass" > > puts "#{$var(if $a == true then "iable" end)}" > > since $a == true, I would like this to become: > puts "#{$variable}" > > But this doesn't work. I didn't expect it to, but is something like > this possible? Am I stuck with this? : > > puts "#{if $a == true then $variable else $var end}" > > > What I'd really like to learn is how I can patch multiple strings > together and call it a variable. I think I'm just missing some simple > piece of this puzzle.. > > The imaginary code would be: > > ab = "pass" > puts ("a" + "b").to_variable > > Or to a global, an instance variable, etc.. envisioned like this: > > puts $("a" + "b") > puts @("a" + "b") > > > If there's a simple way to do this, a code snippet or a pointer to a > manual reference would be all I need. http://www.perl.org :-) Perl has these "soft" or "symbolic" references, plus a whole chorus of people to tell you that you should use hashes instead :-) Ruby gives you ways to examine available existing variables, and you can pry into them: @ab = "pass" puts instance_variable_get("@#{"a" + "b"}") and so on. David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org