Sunday, August 03, 2025
All the Bits Fit to Print
Exploring Ruby’s /o regex modifier and its caching behavior in the VM
A Ruby regex modifier /o
caches the interpolated pattern the first time it is run, causing all subsequent uses to reuse that initial pattern regardless of input changes.
Why it matters: Using /o
can cause unexpected bugs by permanently fixing the regex to the first interpolated value, ignoring later inputs.
The big picture: /o
exists for performance optimization by avoiding repeated interpolation, but in modern Ruby, manual caching is clearer and safer.
Stunning stat: The Ruby VM instruction once
ensures the regex interpolation runs exactly once per literal, across threads, causing non-deterministic first-value caching.
Commenters say: Many recall /o
from Perl, warning it’s rarely worth the confusion and recommend avoiding it; some appreciate the deep dive into Ruby internals.