💡 TIL: Regex within string square brackets
24th February 2025
I’ve always known that Ruby supports ranges within a string’s square brackets. So in addition to the simple `name[4]` I can do `name[2..4]` and `name[2...]` and `name[-1]`. But I just learned you can put regex in the square brackets for more dynamic substring selectors: `“me+abc123@email.com”[/.+\+(.+)@(.+)/, 2]` will give you the subdomain of the email address. It even works with named capture groups! `“123.45”[/(?<dollars>\d+)\.(?<centers>\d+)/, :dollars]` will give you the dollars. The article has a few other notable examples.
More recent articles
- Ruby's clamp method reduces conditionals - 24th February 2025
- Elegant solution to versioning an API - 24th February 2025