A hidden Ruby Regex feature

Josua Schmid
2 min readAug 29, 2019

--

There are quite some ways to do Regex stuff in Ruby. You can look them all up here in the Ruby docs. But there is one problem with most of them: they don’t support a functional way of programming well. Regex in Ruby normally degenerate to an if-statement like this

matchdata = /hay/.match('haystack')if matchdata
# do something with matchdata
end

Named captures don’t help a lot, except if you do fancier things by combining them with the =~-operator:

/(?<thing>hay)/ =~ 'haystack'
=> 0
thing
=> "hay"

You can now directly use thing and pass it to some function to be processed. I still don’t find this very nice because the =~-operator is a language construct which magically creates variables when used with named captures.

There is light at the end of the tunnel — Photo by Aron Van de Pol on Unsplash

The bracket operator on strings to the rescue

The nice solution lies in a different place, namely at the string brackets operator. There you’ll read about two interesting argument sets:

  1. The string brackets operator can take a Regex
  2. The string brackets operator can take a Regex and a capture name.

So look at the following beautiful examples which allow you to keep a fully functional programming style without conditionals:

'haystack'[/hay/]
=> "hay"
'histack'[/hay/]
=> nil
'haystack'[/hay(.*)/, 1]
=> "stack"
'haystack'[/hay(.*)/, 0]
=> "haystack"
'haystack'[/hay(?<thing>stack)/, 'thing']
=> "stack"
'haySTACK'[/hay(?<thing>stack)/, 'thing']
=> nil

--

--

Josua Schmid
Josua Schmid

Written by Josua Schmid

I engineer software and craft beer, or the other way around. Find my old blog here: https://web.archive.org/web/20181108025110/http://blog.schmijos.ch/

No responses yet