Forum: Ruby gsub and single quote issue

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
934f858e451cf9b771996b2940cd696b?d=identicon&s=25 Raj Singh (dorelal)
on 2009-03-24 21:35
a = " Ruby's gem "

puts a.gsub(/[']/, "") #=> 1. Rubys gem

puts a.gsub(/[']/, "'") #=> 2. Ruby's gem

puts a.gsub(/[']/, "\'") #=> 3. Ruby's gem

puts a.gsub(/[']/, "\\'") #=> 4. Rubys gem s gem

puts a.gsub(/[']/, "\\\'") #=> 5. Rubys gem s gem

puts a.gsub(/[']/, "\\\\'") #=> 6. Ruby\'s gem

puts " "


I couldn't understand the result for #4 and #5. Any explanation is
appreciated.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-03-24 22:15
(Received via mailing list)
On 24.03.2009 21:32, Raj Singh wrote:
> puts a.gsub(/[']/, "\\\'") #=> 5. Rubys gem s gem
>
> puts a.gsub(/[']/, "\\\\'") #=> 6. Ruby\'s gem
>
> puts " "
>
>
> I couldn't understand the result for #4 and #5. Any explanation is
> appreciated.

The sequence \' in a replacement string is interpreted as the post
match.  That's why you see the duplication.  You'll see this nicely by
bracketing the replacement:

irb(main):012:0> a = " Ruby's gem "
=> " Ruby's gem "
irb(main):013:0> a.gsub /'/, "<\\'>"
=> " Ruby<s gem >s gem "

There is also pre match:

irb(main):014:0> a.gsub /'/, "<\\`>"
=> " Ruby< Ruby>s gem "

Kind regards

  robert
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2009-03-25 06:21
Robert Klemme wrote:
>
> The sequence \' in a replacement string is interpreted as the post
> match.
>

I assume that has something to do with ruby's crazy global variables,
e.g $'.  In that case, why isn't the '$' required.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-03-25 08:10
(Received via mailing list)
On 25.03.2009 06:18, 7stud -- wrote:
> Robert Klemme wrote:
>> The sequence \' in a replacement string is interpreted as the post
>> match.
>
> I assume that has something to do with ruby's crazy global variables,
> e.g $'.  In that case, why isn't the '$' required.

The replacement string is interpreted by sub and gsub and this is just
the convention that was chosen.  Btw, it's the same convention as in sed
and a number of other regular expression based replacement tools as
well.

Kind regards

  robert
This topic is locked and can not be replied to.