Someone said that Ruby can do anything that Perl does.
How would you write this Perl regex
$s =~ s/(pat1+)pat2(pat3*)/&foo($1,$2)/ge;
in Ruby?
It
- does a global replace (/g) in one sweep
- executes code (calls function) to create the replacement string (/e)
- uses parts of the searched patterns (groupings) as parameters to foo
My books
- Ruby in a Nutshell
- The Ruby Way
are very brief with respect to regexs and don’t give
me a clue how to do this.
···
–
Helmut Leitner leitner@hls.via.at
Graz, Austria www.hls-software.com
Helmut Leitner wrote:
Someone said that Ruby can do anything that Perl does.
How would you write this Perl regex
$s =~ s/(pat1+)pat2(pat3*)/&foo($1,$2)/ge;
in Ruby?
str.gsub /(pat1+)pat2(pat3*)/ { |m| foo(m[1], m[2]) }
Note that it;s better to use m[1] and m[2] instead of $1/$2 …
Happy new year!
Helmut Leitner helmut.leitner@chello.at wrote in message news:3E116DDE.972A9081@chello.at…
Someone said that Ruby can do anything that Perl does.
How would you write this Perl regex
$s =~ s/(pat1+)pat2(pat3*)/&foo($1,$2)/ge;
in Ruby?
str = “There are 3*33 bottles of beer on the wall.”
def foo(a,o,b)
case o
when ‘+’ then (a.to_i + b.to_i).to_s
when ‘-’ then (a.to_i - b.to_i).to_s
when ‘*’ then (a.to_i * b.to_i).to_s
when ‘/’ then (a.to_i / b.to_i).to_s
end
end
p str.gsub(/^(\D+)(\d+)\s*([+-/])\s(\d+)(\D+)/) {$1+foo($2,$3,$4)+$5}