13

Ruby regexp has some options (e.g. i, x, m, o). i means ignore case, for instance.

What does the o option mean? In ri Regexp, it says o means to perform #{} interpolation only once. But when I do this:

a = 'one'  
b = /#{a}/  
a = 'two'  

b does not change (it stays /one/). What am I missing?

sawa
  • 156,411
  • 36
  • 254
  • 350
Liao Pengyu
  • 581
  • 3
  • 11
  • You are not using the `o` flag in your regexp. Why are you expecting any effect of it? – sawa Nov 11 '12 at 23:29
  • Well, if using `o` flag means turn on the effect, then i though the `#{}` in a regexp may execute everytime without the flag – Liao Pengyu Nov 12 '12 at 05:32
  • 1
    Beware that in the Perl (as opposed to Ruby) docs http://perldoc.perl.org/perlre.html it is stated of the `o` modifier: "pretend to optimize your code, but actually introduce bugs". So in Perl, the `o` flag seems to have a different meaning to that of Ruby, and furthermore the Perl flag may be broken. – Rhubbarb Sep 23 '14 at 09:33

1 Answers1

20

Straight from the go-to source for regular expressions:

/o causes any #{...} substitutions in a particular regex literal to be performed just once, the first time it is evaluated. Otherwise, the substitutions will be performed every time the literal generates a Regexp object.

I could also turn up this usage example:

# avoid interpolating patterns like this if the pattern
# isn't going to change:
pattern = ARGV.shift
ARGF.each do |line|
    print line if line =~ /#{pattern}/
end

# the above creates a new regex each iteration. Instead,
# use the /o modifier so the regex is compiled only once

pattern = ARGV.shift
ARGF.each do |line|
    print line if line =~ /#{pattern}/o
end

So I guess this is rather a thing for the compiler, for a single line that is executed multiple times.

Martin Ender
  • 40,690
  • 9
  • 78
  • 120
  • 1
    Just a second ago I read a wiki about `Evaluation strategy`, I finally understand a lot. In ruby, assignment do the eager evaluation, so after the segment `b = /#{a}/`, `b` be assigned to `/one/`, that's to say, 'there is nothing business with the `o` flag' – Liao Pengyu Feb 04 '13 at 08:20
  • This answer has been added to the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), under "Modifiers". – aliteralmind Apr 10 '14 at 00:36