/o (Once (interpolate once))
What is /o (Once (interpolate once))?
/o (Once (interpolate once)): Tells the engine to interpolate #{...} variables into the pattern only once, on first use, and cache the compiled result. The o flag in Ruby means interpolate once. A pattern like /#{prefix}\d+/o builds the regex from the variable the first time the line runs, then keeps using that compiled version, even if prefix changes later.
Frequently asked questions about /o (Once (interpolate once))
How is /o (Once (interpolate once)) used in practice?
It was a performance trick from a time when compiling a regex inside a loop was expensive. Today Ruby caches regex literals well, and the gain is usually too small to measure.
What should you keep in mind with /o (Once (interpolate once))?
The cost is a confusing bug. If the variable changes, the pattern silently does not. Someone reading the code sees prefix and reasonably assumes the current value is used. If you need a fixed pattern, build it once outside the loop and store it in a constant or a variable with a clear name. That gives the same speed and makes the behaviour obvious to the next person.
At a glance
| Category | Regex flags |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |