Perhaps I’m missing the point, but what semantic have consecutive
backslashes substituting a string ?
I feels like a bug, but probably isn’t:
irb(main):008:0> puts “abcd”.sub(‘abcd’,“\”).length
1
irb(main):014:0> puts “abcd”.sub(‘abcd’,“\”*2).length
1
irb(main):009:0> puts “abcd”.sub(‘abcd’,“\”*10).length
5
Thx a lot,
benedikt
···
On Tue, 06 Apr 2004 23:01:55 +0900, Robert Feldt wrote:
ts wrote:
…
svg% ruby -e ‘p “abcdef”.sub(/(.).(…)/, “\+”)’
“cdef”
svg%
…
Yeah, that’s right the “last matched group”; I don’t use that one much
apparently…
- match a char, followed by another char. followed by two more chars.
remember the last two chars (and the first)
- replace the entire match with the remembered last two chars (which is
the 'last matched group')
abcdef -> cdef
----
-- --
The somewhat confusing part is that a backslash in a gsub that doesn’t
translate to a substitution expression becomes a literal. So, since
there is nothing for the last backslash to escape:
… another reason why, as someone pointed out in a thread earlier this
month, it’s handy to only use the block form, and avoid the argument
form of (g)sub like the plague
cheers,
–Mark
···
On May 10, 2004, at 11:38 AM, Benedikt Huber wrote:
On Tue, 06 Apr 2004 23:01:55 +0900, Robert Feldt wrote:
ts wrote:
…
svg% ruby -e ‘p “abcdef”.sub(/(.).(…)/, “\+”)’
“cdef”
svg%
…
Yeah, that’s right the “last matched group”; I don’t use that one much
apparently…
Perhaps I’m missing the point, but what semantic have consecutive
backslashes substituting a string ?
I feels like a bug, but probably isn’t:
irb(main):008:0> puts “abcd”.sub(‘abcd’,“\”).length
1
irb(main):014:0> puts “abcd”.sub(‘abcd’,“\”*2).length
1
irb(main):009:0> puts “abcd”.sub(‘abcd’,“\”*10).length
5
match a char, followed by another char. followed by two more chars.
remember the last two chars (and the first)
replace the entire match with the remembered last two chars (which is
the ‘last matched group’)
abcdef → cdef
-- --
Yes, and further: If you want to do substitutions and aren’t sure there
will be no backslash sequences in the replacement string you should use
the block form, like so:
$ ruby -e ‘p “a”.sub(“a”) {“\+”}’
“\+”
I added a note to my code review checklist to “always” use the block
form…
Sorry for wasting bandwidth on this; I should have read the docs more
closely.