From: Robert Dober Date: 2007-06-30T20:51:07+09:00 Subject: Re: question: referencing a variable with a variable On 6/13/07, 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. > > 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} Sorry if I am asking something stupid here but my $perl ;) days are long gone now. You are matching the reference of a sub with a rgexp and then call the sub you are holding the reference of??? Assuming that you meant something like if (whatever) {&$choice} you will write if whatever choice.call The interesting difference will be the call of my_sub, which I have to call my_def in Ruby ;). def my_def callable #now callable could be a lambda my_def lambda{ puts 42 } #a method s="*" * 42 m = s.method(:size) my_def m But very probably you want to use something more Rubish. def my_def ... yield if something # with many variations available Proc.new.call if something The next approach -- my preferred -- will give you a reference to the block - a little bit like an anonymous sub in perl. def my_def ..., &blk blk.call if something end > > example 2: > > $this = 'var_name'; > $var_name = 'i want this to print'; > print $$var_name . "\n"; > > thanks this = "var_name" var_name = "I want #{this} to print" puts var_name I am aware of the conceptional difference -- and that was nicely explained already :) - but maybe that is all you need ;) HTH Robert -- I always knew that one day Smalltalk would replace Java. I just didn't know it would be called Ruby -- Kent Beck