Efficient way to do a simple Perl thing with Ruby

K

Kirk Haines

I have some Perl code that does something like this:

$copy =~ s{<!--#include\s+virtual\s*=\s*"([^"]*)"\s*-->}{get($1)}gem

Basically, apply a regex to a string, and for every match, call get($1) and
replace the match with the return value of the get(). get() comes from
LWP::Simple, and simply fetches the content at the given URL.

My Ruby-fu is failing me at coming up with a relatively concise yet readable
way to do this in Ruby. My implementation is, I am sure, much longer than
necessary.

So, anyone have any ideas? How would you do this?


Kirk Haines
 
K

Kirk Haines

On Fri, 9 Jul 2004 01:21:29 +0900, Kirk Haines wrote
My Ruby-fu is failing me at coming up with a relatively concise yet
readable way to do this in Ruby. My implementation is, I am sure,
much longer than necessary.

So, anyone have any ideas? How would you do this?

And....nevermind. I figured out where I was being thick. gsub with a block
works nicely.


Kirk Haines
 
R

Randy Lawrence

Kirk said:
On Fri, 9 Jul 2004 01:21:29 +0900, Kirk Haines wrote




And....nevermind. I figured out where I was being thick. gsub with a block
works nicely.


Kirk Haines

We ran into the same question earlier today. Maybe the documentation
for String.sub() should mention String.gsub(). I think it would have
been more intuitive to have an optional parameter to sub() for
global/case-insenstive/etc.
 
R

Robert Klemme

Randy Lawrence said:
We ran into the same question earlier today. Maybe the documentation
for String.sub() should mention String.gsub().

Good point.
I think it would have
been more intuitive to have an optional parameter to sub() for
global/case-insenstive/etc.

Case sensitivity is controlled by a regular expression flag.

About gsub vs. sub with a paramter that controls global replacement: while
that might mimic what vi does, it's generally considered better style to
have separate methods if behavior differs than to have a single method
whose behavior is controlled by flags. Also it's more efficient, too.

Kind regards

robert
 
G

Graham Nicholls

Randy said:
We ran into the same question earlier today. Maybe the documentation
for String.sub() should mention String.gsub().
Funny, I wrote "see gsub for global occurrences" in "Programming Ruby's"
chapter 22 about half an hour ago. It ought to have been there already,
IMNSHO.
Graham
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top