Gsub question

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

···


A.D. 1844: Samuel Morse invents Morse code. Cryptography export
restrictions prevent the telegraph’s use outside the U.S. and Canada.

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.

$1 is evaluated before the matching happens, and since you didn’t match
anything yet, $1 is the empty string. Do this instead:

ruby -e ‘a=“hello hi hello”;a.gsub!(/(\w+)/,“\1a”); puts a’
helloa hia helloa

Peter

Daniel Bretoi wrote:

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

···


Jamis Buck
jgb3@email.byu.edu

ruby -h | ruby -e ‘a=;readlines.join.scan(/-(.)[e|Kk(\S*)|le.l(…)e|#!(\S*)/) {|r| a << r.compact.first };puts “\n>#{a.join(%q/ /)}<\n\n”’

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

···

On 2003-12-17, Daniel Bretoi lists@debonair.net wrote:

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