1 min read

TIL: How to Quickly Get Regex Matches in Ruby

I often want to get the string from a regex match. If I'm only bothered about getting the first match, this shorthand works

I often want to get the string from a regex match. If I'm only bothered about getting the first match, this shorthand works.

'hello world'[/hello/]
# "hello"

'hello world'[/goodbye/]
# nil

But there's more. If I wanted to over write the part that matches, I can.

string = 'hello world'
string[/hello/] = 'goodbye'
puts string
# goodbye world