gsub question

Discussion in 'Ruby' started by Daniel Bretoi, Dec 17, 2003.

  1. 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.
    Daniel Bretoi, Dec 17, 2003
    #1
    1. Advertising

  2. On 2003-12-17, 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
    >


    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
    Jason Williams, Dec 17, 2003
    #2
    1. Advertising

  3. Daniel Bretoi

    Jamis Buck Guest

    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


    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"'
    Jamis Buck, Dec 17, 2003
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dirk Einecke

    Syntax question for gsub

    Dirk Einecke, Jul 11, 2004, in forum: Ruby
    Replies:
    11
    Views:
    434
    Chris Dutton
    Jul 12, 2004
  2. mss
    Replies:
    5
    Views:
    109
    James Edward Gray II
    Jan 20, 2005
  3. aurelianito

    gsub and gsub! are inconsistent

    aurelianito, Nov 8, 2005, in forum: Ruby
    Replies:
    9
    Views:
    162
    Robert Klemme
    Nov 9, 2005
  4. Hoppy

    gsub method question

    Hoppy, May 10, 2006, in forum: Ruby
    Replies:
    4
    Views:
    85
    Hoppy
    May 10, 2006
  5. x1
    Replies:
    4
    Views:
    138
Loading...

Share This Page