From: "misaka@..." Date: 2007-06-14T20:15:03+09:00 Subject: Re: question: referencing a variable with a variable On Jun 13, 10:26 pm, knohr wrote: > I come from a perl background. I have gotten in the habit of using > references to variables instead of specifically calling said variable/ > class/whatever. I don't think that symbolic references directly supported in Ruby, but as Phrogz pointed out there are certain methods to access variables and methods by using a string representation of their name. > > Basically, I am wondering how I would translate the following into > ruby. > > example 1: > sub my_sub > { > $choice = shift; > $choices="this|that|foo|bar"; > if ( $choice =~ m/($choices)/ ) {&$choice} > else {die "some witty msg"} > } This one is easy, there's a "send" method that let's you call a method using a string containing it's name. Here's an abbreviated version of what you have above: def my_sub( $choice ) if $choice =~ /foo|bar/ send( $choice ) end end > example 2: > > $this = 'var_name'; > $var_name = 'i want this to print'; > print $$var_name . "\n"; Looks like this would probably need an eval: this = 'var_name' var_name = 'i want this to print' puts( eval( this ) ) There are methods to list local variables 'local_variables', and return instance variables, but there isn't really anything to actually return the value of a local variable so far as I can see. --Misha