Skip to content

Instantly share code, notes, and snippets.

@robmiller
Last active March 3, 2017 03:14
Show Gist options
  • Save robmiller/9875950 to your computer and use it in GitHub Desktop.
Save robmiller/9875950 to your computer and use it in GitHub Desktop.
Explaining Ruby regex's /o modifier
require "benchmark"
def letters
puts "letters() called"
sleep 0.5
"A-Za-z"
end
words = %w[the quick brown fox jumped over the lazy dog]
Benchmark.bm do |bm|
bm.report("without /o:\n") do
words.each do |word|
puts "Matches!" if word.match(/\A[#{letters}]+\z/)
end
end
bm.report("with /o:\n") do
words.each do |word|
puts "Matches!" if word.match(/\A[#{letters}]+\z/o)
end
end
end
@robmiller
Copy link
Author

An explanation:

The o modifier causes the interpolation to happen once; the result of the interpolated regex is, for all intents and purposes, memoised.

So if you're matching a regular expression in a loop, and interpolating something that's the result of an expensive calculation (here simulated with a sleep), using the o modifier will greatly speed up your code.

Admittedly, those are uncommon circumstances. But it's one to keep in mind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment