Regular expression matching in Ruby with String#[]

04 Jun 2015

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.

s="Hello, world!"# Return sub-string if presents['world']#=> 'world'# Returns nil if not presents['bye']#=> nil# We can also use regular expressions theres[/e..o/]#=> 'ello'# Capture the last word in the strings[/ ([a-zA-z]*)([^ ]*)$/,1]#=> 'world'

Hi, I’m Nithin Bekal.
I work at Shopify in Ottawa, Canada.
Previously, co-founder of
CrowdStudio.in and
WowMakers.
Ruby is my preferred programming language,
and the topic of most of my articles here,
but I'm also a big fan of Elixir.
Tweet to me at @nithinbekal.