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/.
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
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/\.
--
Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/
The "`Stok' disclaimers" apply.
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
--
Posted via http://www.ruby-forum.com/\.