Forum: Ruby String gsub returns an empty string, a bug?

Eb09971d094064715158fbebe2176204?d=identicon&s=25 Sami S. (sami_s)
on 2013-09-15 16:21
Why does the first line return an empty string? Is this a bug or a
feature?

irb(main):001:0> a = "x"; a.gsub!("x","\\'")
=> ""
irb(main):002:0> a = "x"; a.gsub!("x","y")
=> "y"
2ffac40f8a985a2b2749244b8a1c4161?d=identicon&s=25 Mike Stok (Guest)
on 2013-09-15 17:07
(Received via mailing list)
On 2013-09-15, at 10:21 AM, "Sami S." <lists@ruby-forum.com> wrote:

> Why does the first line return an empty string? Is this a bug or a
> feature?
>
> irb(main):001:0> a = "x"; a.gsub!("x","\\'")
> => ""
> irb(main):002:0> a = "x"; a.gsub!("x","y")
> => "y"
>
> --
> Posted via http://www.ruby-forum.com/.

There are extra backslash sequences which work in substitution strings:

[1] pry(main)> a = "wxy"; puts a.gsub!("x","\\'")
wyy
=> nil

Here \' is the "remains" of the string after the match, in the Pickaxe
book it tells about the additional backslash sequences in substitution
strings:

\& last match
\+ last matched group
\` string prior to match
\' string after match
\\ literal backslash

So you need to escape the \ in \' to stop it being interpreted as the
string after match e.g.

[2] pry(main)> a = "wxy"; puts a.gsub!("x","\\\\'")
w\'y
=> nil

Another approach might be to use a block where the returned string isn't
using the additional backslash sequences:

[3] pry(main)> a = "wxy"; puts a.gsub!("x") { "\\'" }
w\'y
=> nil

Hope this helps,

Mike


--

Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
Eb09971d094064715158fbebe2176204?d=identicon&s=25 Sami S. (sami_s)
on 2013-09-15 18:04
Thank you for your answer. I've been reading the class reference at
(http://ruby-doc.org/core-2.0.0/String.html) which doesn't mention the
backslash sequences..


regards,
Sami

Mike Stok wrote in post #1121503:
> On 2013-09-15, at 10:21 AM, "Sami S." <lists@ruby-forum.com> wrote:

> Here \' is the "remains" of the string after the match, in the Pickaxe
> book it tells about the additional backslash sequences in substitution
> strings:
>
> \& last match
> \+ last matched group
> \` string prior to match
> \' string after match
> \\ literal backslash
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.