Regex

I wanted to give a quick tip on something I recently discovered about regex and Ruby, while trying to look for some regex to use.

This is a journey of self discovery... Wait, no, that's not right. It was definitely an adventure. And it started when the search for a particular regex got mashed up with knowing Rubocop preferring string literals to be immutable with .freeze. Oh, how we dive into rabbit holes.

Immutability

As mentioned above, string literals should be made immutable with .freeze. It's a thing that Rubocop picks up on and alerts you. .freeze does 2 things: one, the object can't be changed (immutable), and two, it doesn't create as many objects, so in terms of memory use, it's hella beneficial.

Click here to read a fantastic article that talks about this exact thing in a much better way than I can.

Now, knowing this, I wondered if I could do something similar with regex. While Googling for it, I came upon a discussion on exactly this topic in the Ruby developer forums.

And I found out that Ruby has immutable regex. This is great news!

But, more importantly? Dynamic Regex

Dynamic Regex

Admittedly I didn't know that regex could be dynamic, but given that this is Ruby we're talking about, I should have assumed it. From the link above, user Eregon provides examples, and they speak for themselves. But I've re-done them in my own console to confirm:

def dynamic_regex
  /ab#{3}/
end

2.2.4 :057 > dynamic_regex.object_id
 => 70175794398600
2.2.4 :058 > dynamic_regex.object_id
 => 70175794381460

def dynamic_regex_frozen
  /ab#{3}/o
end

2.2.4 :052 > dynamic_regex_frozen.object_id
 => 70175794516740
2.2.4 :053 > dynamic_regex_frozen.object_id
 => 70175794516740

I never knew this was even a thing. I'm glad I know about it, though I don't know when I'll ever use it. But, it's a little bit of knowledge gained.

Level up +2


Questions? Comments? Hit me up at risaonrails !