Tech News
← Back to articles

The /o in Ruby regex stands for "oh the humanity "

read original related products more articles

Your code using the /o modifier Source: wikipedia

Hi there! Do you like Regex? Do you like performance? Do you like creating confounding bugs for yourself rooted in the mechanics of the Ruby VM itself?

If you said yes to all of the above, have I got a feature for you!

But first, let’s start with a story.

The cliffs of insanity

I was recently reviewing some code, and part of the functionality was about matching. A class took an array of strings, and you could call a method to see if an input matched part of any of the strings. Stripped down, it was effectively the following code:

class Matcher def initialize(matchables) @matchables = matchables end def matches_any?(input) @matchables.any? { |m| m.match?(/#{input}/io) } end end

I know there are some of you reading this code and thinking “does this really need a regex?”, “couldn’t it just use include? and some downcasing?”, “does this even need to exist?”, etc, etc. I see you, I hear you, I’d probably think the same, and I promise you the specifics of this method aren’t that important.

Functionally, the code looked ok to me. I knew what /i was (a regex in case-insensitive mode), but I didn’t recognize /o . It didn’t seem critically important to lookup yet. Tests were not exhaustive but were green, and so I went to run the code in a console:

Matcher . new( [ "Ruby!" ] ) . matches_any?( "ruby" ) => true Matcher . new( [ "Ruby!" ] ) . matches_any?( "something else" ) => true Matcher . new( [ "Ruby!" ] ) . matches_any?( "javascript" ) => true

... continue reading