From: Tasos Laskos on
Hi guys,

I'm using "ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux]"
and just noticed a possible bug in Regex.escape() while using it with
gsub()


This:
--------
pp Regexp.escape( '.rb' )
--------

yields:
--------
"\\.rb"
--------

while it should be "\.rb".

Regexp.new( '.rb' ) or Regexp.new( '\.rb' ) work though, they replaces
the ".rb" string as expected.
Yes I know that "Regexp.new( '.rb' )" works incidentally but I'm just
mentioning it. :)
--
Posted via http://www.ruby-forum.com/.

From: Joel VanderWerf on
Tasos Laskos wrote:
> Hi guys,
>
> I'm using "ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux]"
> and just noticed a possible bug in Regex.escape() while using it with
> gsub()
>
>
> This:
> --------
> pp Regexp.escape( '.rb' )
> --------
>
> yields:
> --------
> "\\.rb"
> --------
>
> while it should be "\.rb".
>
> Regexp.new( '.rb' ) or Regexp.new( '\.rb' ) work though, they replaces
> the ".rb" string as expected.
> Yes I know that "Regexp.new( '.rb' )" works incidentally but I'm just
> mentioning it. :)

It is correct, because it lets you do this:

>> dot_rb = Regexp.escape( '.rb' )
=> "\\.rb"
>> /file#{dot_rb}/ =~ "file.rb"
=> 0
>> /file#{dot_rb}/ =~ "fileQrb"
=> nil

Note that "\\.rb" is the same string as '\.rb'.


From: Robert Klemme on
On 28.06.2010 19:31, Tasos Laskos wrote:
> Hi guys,
>
> I'm using "ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux]"
> and just noticed a possible bug in Regex.escape() while using it with
> gsub()
>
>
> This:
> --------
> pp Regexp.escape( '.rb' )
> --------
>
> yields:
> --------
> "\\.rb"
> --------
>
> while it should be "\.rb".

No, it should be as it is as Joel explained. Note also

irb(main):007:0> puts Regexp.escape( '.rb' )
\.rb

It is the representation of the string that includes a backslash to
properly escape the backslash:

irb(main):010:0> "\\n".size
=> 2
irb(main):011:0> "\n".size
=> 1
irb(main):012:0> puts "\\n"
\n
=> nil
irb(main):013:0> puts "\n"

=> nil


> Regexp.new( '.rb' ) or Regexp.new( '\.rb' ) work though, they replaces
> the ".rb" string as expected.
> Yes I know that "Regexp.new( '.rb' )" works incidentally but I'm just
> mentioning it. :)

It works but it does not match the sequence ".rb" - rather it matches
any character followed by "rb":

irb(main):004:0> r = Regexp.new( '.rb' )
=> /.rb/
irb(main):005:0> r.match '.rb'
=> #<MatchData ".rb">
irb(main):006:0> r.match 'oooopsrb'
=> #<MatchData "srb">

Kind regards

robert


--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/