From: Jim Freeze Date: 2002-11-16T05:18:22+09:00 Subject: Re: Regexp: What does //o do? On Saturday, 16 November 2002 at 2:03:24 +0900, Matt Armstrong wrote: > Jim Freeze writes: > > > On Friday, 15 November 2002 at 15:23:16 +0900, > > nobu.nokada@softhome.net wrote: > >> Hi, > >> > >> At Fri, 15 Nov 2002 15:02:51 +0900, > >> Jim Freeze wrote: > >> > In a regex, what is the /o for (as opposed to n, i or g)? > >> > > >> > EG > >> > re = /\A\s+/o > >> > >> This o has no meanings. It's usefull with interpolation. > >> > >> ['\A\s+', '\S+\z'].map {|s| /#{s}/} # => [/\A\s+/, /\S+\z/] > >> ['\A\s+', '\S+\z'].map {|s| /#{s}/o} # => [/\A\s+/, /\A\s+/] > >> > > > > I'm confused. Why does it affect the map iterator? > > > > ['a','b'].map {|s| /#{s}/o} # => [/a/,/a/] > > Perhaps this is more clear: > > irb(main):009:0> def foo(arg) > irb(main):010:1> p /#{arg}/o > irb(main):011:1> end > nil > irb(main):012:0> foo('a') > /a/ > nil > irb(main):013:0> foo('b') > /a/ > nil > > > In other words, /o means the regexp will be compiled the first time > the particular piece of code executes and the same regexp will be used > from then on. Use it only when you know the regexp will always be the > same anyway. These two examples show how it can actually introduce > bugs into your code. > Yes. It's not completely clear to me when it will be recompiled and when it won't be. Above it is not. Below it is. irb(main):001:0> s="a" "a" irb(main):002:0> /#{s}/o /a/ irb(main):003:0> s="b" "b" irb(main):004:0> /#{s}/o /b/ I thought that your example above with the function would give the same results as the irb example above because the re would get destroyed when the function returned. Then I tried this: irb(main):016:0> def foo(s) irb(main):017:1> re = /#{s}/o irb(main):018:1> p re irb(main):019:1> re = nil irb(main):020:1> end nil irb(main):021:0> foo("a") /a/ nil irb(main):022:0> foo("b") /a/ nil and I'm confused even more. -- Jim Freeze ---------- Tonight's the night: Sleep in a eucalyptus tree.