Welcome to day 14 of the 49 Days of Ruby! 🎉
After 13 days of learning some of the core concepts in programming through Ruby, we are going to take a small detour and discuss regular expressions. There is indeed Ruby implementations for handling regular expressions (regex), but the topic itself is worth focusing on for a bit.
A regular expression, regex for short, is a set of characters that allow you to compose a search pattern. You can use that search pattern to traverse through data to find a match.
You can imagine how helpful something like that is!
However, its usefulness is often overshadowed by its complexity. Regex can be very difficult to compose and to break down.
Thankfully, there are tools to help you in composing and understanding a regular expression. We'll highlight them in just a moment.
The best way to understand Regex is to see an example.
order_number = "456-222-1111" order_number.gsub!(/\D/, "") # => "4562221111"
The Ruby method
#gsub! is used to replace the matching characters with the replacement text. The pattern to match against, the regex, is in the first half of the method. The replacement text is in the second half, after the comma.
In the example above, the regex pattern of
\D looks for any non-digit. The
#gsub! method searches for that pattern and then replaces it with an empty string. You could also replace it with anything else.
The result is the
order_number now holds a string with all the dashes removed.
The example we showed is a fairly straightforward use case. Regex can get a lot more complex. Take a look at this example from Stack Overflow:
/\d+(?=:)|\d+(?=,\|,\d)|(?<=\d,\|,)\d+/. Talk about making your head spin!
Thankfully, there are some tools available to lend you a hand.
If you want to explore Regex more, both in Ruby and generally, here are some good places to check out:
That's it for now! Enjoy your learning and see you tomorrow!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.