Last active
March 3, 2017 03:14
-
-
Save robmiller/9875950 to your computer and use it in GitHub Desktop.
Explaining Ruby regex's /o modifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An explanation:
The
omodifier 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 theomodifier will greatly speed up your code.Admittedly, those are uncommon circumstances. But it's one to keep in mind.