The /o in Ruby regex stands for "oh the humanity "
9 months ago
- #Regex
- #Performance
- #Ruby
- The article discusses the `/o` modifier in Ruby's regular expressions, which caches the interpolated regex after its first evaluation.
- Using `/o` can lead to unexpected behavior where the regex only evaluates the first input it receives, ignoring subsequent inputs.
- The modifier was originally intended as a performance optimization but can cause non-deterministic and hard-to-debug issues.
- The article explores the Ruby VM's `once` instruction, which is used to implement the `/o` modifier's caching behavior.
- Examples demonstrate how the `/o` modifier can lead to thread non-determinism and recursive evaluation quirks.
- The article advises against using `/o` due to its unpredictable behavior and suggests manual caching as a safer alternative.
- A humorous example shows how the `/o` modifier can be (mis)used to create a thread-safe, one-time execution block.
- The `END` syntax in Ruby also uses the `once` instruction, revealing another use case for this VM feature.