From: Emmanuel Surleau Date: 2008-08-29T05:11:54+09:00 Subject: Re: How would this Perl script look in Ruby? ------=_Part_12201_16185290.1219954595255 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On Thu, Aug 28, 2008 at 2:51 PM, Robert Klemme wrote: > 2008/8/28 Avinash Magar : > > Nathan Powell wrote: > >> Why don't you show us what you have, and where you are stuck, rather > >> than us translating it for you in it's entirety. > >> > > sorry about that. > > things I would like to know are: > > > > 1) How would we write following method? > > the one which takes an array and return subref (whatever equivalent > > in Ruby) > > something like this(in perl) > > sub get_random_val_generator { > > my $arr =3D shift; > > return sub { return $arr->[ rand @$arr] }; > > } > > You can do > > array =3D ... > rand_gen =3D lambda { array[rand(array.size)] } > ... > item =3D rand_gen[] # or > item =3D rand_gen.call > > > 2) How to store these references(subrefs) in a hash or some variable? > > hash[some_key] =3D some_object # everything is an object > > > 3) How would you do(approach) this in Ruby(the script)? > > My Perl is a bit rusty and, frankly, I'm not inclined to spent the > efforts to analyze it. Can you describe it? Unless I'm mistaken, the gist of it is: Take a bunch of templates: adm has _QTY_ _CAR_ cars ssn has _QTY_ _CAR_ cars In an infinite loop, pick one randomly, and replace the _QTY_ and _CAR_ placeholders by values taken from the 'vals' fields in the following hash: my %value_map =3D ( '_CAR_' =3D> { 'order' =3D> 'rand', 'vals' =3D> [qw(bentley merc bmw audi porsche ford honda lexus)] }, '_QTY_' =3D> { 'order' =3D> 'rand', 'vals' =3D> [1..10] } ); The way values are chosen depends on the 'order' field, which can be either random ('rand') or sequential ('seq'). In ruby, you could replace the value_map by using a more class-oriented approach: RandomMessageValue.new(:qty, (1..10).to_a) RandomMessageValue.new(:car, %w(bentley merc bmw audi porsche ford honda lexus) And you have SeqMessageValue if you want something sequential. Both RandomMessageValue and SeqMessageValue inherit from MessageValue. A MessageValue object knows how to choose the next value in the array of values (with different implementations). Then you just need a Message class= , which has a list of templates, and a list of MessageValue objects. Message knows how to replace the content of a MessageValue inside a template. Voil=E0. Cheers, Emm ------=_Part_12201_16185290.1219954595255--