DELAPARRA
Index
Color
NL
Category: Regex flags

/o (Once (interpolate once))

Explained by Updated

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.

Definition source Coders Lingo, CC BY 4.0

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

CategoryRegex flags
Explained by
Updated

More Regex flags terms

All terms starting with a number or symbol

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.