gsub question

D

Daniel Bretoi

perl -e '$a="hello hi hello";$a =~ s/(\w+)/$1a/g;print $a; '
helloa hia helloa

ruby -e 'a="hello hi hello";a.gsub!(/(\w+)/,"#{$1}a"); puts a'
a a a

Why? I'm expecting the same result as in perl.

ruby -e 'a="hello hi hello";a.gsub!(/(\w+)/) { |k| k = k + "a"}; puts a'
helloa hia helloa

does however work.

Can someone try to explain why the first doesn't work?

db
 
J

Jason Williams

perl -e '$a="hello hi hello";$a =~ s/(\w+)/$1a/g;print $a; '
helloa hia helloa

ruby -e 'a="hello hi hello";a.gsub!(/(\w+)/,"#{$1}a"); puts a'
a a a

The interpolation (AIUI) is done before the string gets passed to
gsub!, so gsub! sees just the string "a". I think you want

a="hello hi hello";a.gsub!(/(\w+)/,'\1a'); puts a
 
J

Jamis Buck

Daniel said:
perl -e '$a="hello hi hello";$a =~ s/(\w+)/$1a/g;print $a; '
helloa hia helloa

ruby -e 'a="hello hi hello";a.gsub!(/(\w+)/,"#{$1}a"); puts a'
a a a

Why? I'm expecting the same result as in perl.

Because the $1 isn't defined at the time the replacement string is
parsed. Instead, use \1:

ruby -e 'a="hello hi hello";a.gsub!(/(\w+)/, '\1a');puts a'
hello hia helloa
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top