March 19, 2024

My Journey Of Learning Programming Through Flatiron School #16

My name is Mason Ellwood, and I’m currently working on Flatiron School’s Online Full Stack Web Development Program. Each week, I’ll be writing about my experience, what I’m learning, and tips on learning to code.

With this article we are going to take a few steps backward. Even though we are going to still be speaking within Object Oriented Ruby, we need to talk about a useful tool that makes the movement of information incredibly easy. With the use of Regex, you as the developer, can easily pull and place data from large libraries into the program or application you are building. We use a regular expression to encode patterns for matching, searching, and substitution.

RegEx came out in the 1950’s in various forms. Ken Thompson, who created the the first version of Regex in the editor QED as a means to match patterns to text files. Since then there have been multiple various implementations of regular expressions developed. But for this example and more importantly for this course we will be using Ruby regular expression.

Regular expression is a powerful way to search through strings and blocks to find and extract for specific patterns. They can be used for data validation, searching, mass file renaming, and finding records in a database.

One great place to test Ruby Regex is Rubular (http://rubular.com/). This site allows you to test RegEx against text that you define.

In Ruby, regular expressions are generally written between forward slashes.

  • /Your RegEx/

For example, when writing /mason/ this will find all the instances of the mason string. With the use of metacharacters, this allows you to use pre-defined shorthand to match specific characters.

  • \d – will match any digit in your text
  • \w – will match any word character (letters, numbers, characters)
  • \W – to match non-word characters in your text

There are much more metacharacters than these listed, but I will leave that up to you to explore.

With these metacharacters and the use of RegEx, you can then integrate them into Ruby methods.

Using defined Ruby methods before your implementation of RegEx will export different effects. For example:

  • .scan – returns an array of all the items in your string that match a given Regular Expression.
  • .match – returns the first item in your string that matches a given Regular Expression as a match data object.
  • .grep – Grep is an enumerable method for pattern searching in arrays and hashes.

Using these defined Ruby methods in congruence with RegEx will allow you to quickly sift through large or small groups of text to pull only pertinent information. Learning and understanding RegEx allowed me to see and better understand the movement of information from location to location.

Leave a Reply

Your email address will not be published. Required fields are marked *