Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > gsub question

Reply
Thread Tools

gsub question

 
 
Daniel Bretoi
Guest
Posts: n/a
 
      12-17-2003
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.

 
Reply With Quote
 
 
 
 
Jason Williams
Guest
Posts: n/a
 
      12-17-2003
On 2003-12-17, Daniel Bretoi <(E-Mail Removed)> 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
>


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
 
Reply With Quote
 
 
 
 
Jamis Buck
Guest
Posts: n/a
 
      12-17-2003
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
http://www.velocityreviews.com/forums/(E-Mail Removed)

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"'



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Regexp Question / gsub Question x1 Ruby 4 09-26-2006 01:52 AM
gsub method question Hoppy Ruby 4 05-10-2006 06:17 PM
gsub and gsub! are inconsistent aurelianito Ruby 9 11-09-2005 01:38 PM
Yet another gsub question. mss Ruby 5 01-20-2005 04:48 PM
Syntax question for gsub Dirk Einecke Ruby 11 07-12-2004 12:07 AM



Advertisments