Regular expression matching in Ruby with String#[]
Today I learned a new way
to check if a string matches
a regular expression pattern in Ruby.
Strings have a #[]
method
that lets us work with indexes,
but we could also use them
to check if a substring or a pattern exists.
So this allows us to do things like extracting parts of a string.
Because it returns nil when there is not match, we can also use it in conditions:
This is yet another Ruby idiom that seems completely natural once you start using it. I’m surprised I haven’t come across this before.
Tags: ruby