Regexp Implementation in Ruby

Mehdi Farsi
Mar 4, 2018 · 2 min read

The Regexp class

There is 3 ways to instantiate a Regexp

So, the next question is: how to match this Regexp against a String ?

The MatchData class

The Regexp#match method returns an instance of MatchData.

The MatchData class encapsulates all the results of a pattern match.

I invite you to read the official documentation to learn what you can do with an instance of MatchData .

For example, you can use the MatchData#to_a to iterate through the results.

Ruby Magic Variables

The Pattern-Matching Operator =~

Note that all the magic variables are set because the =~operator instantiate a MatchDataif the Regexp matches against the String .

The Named Captures

The named capture feature is also available with the Regexp#match method. The main difference is that there is no variable created. In effect, the named captures are available in the returned MatchData instance by using the MatchData#[] method

To go further

Anyway, you can find a link to the official documentation on each of the following methods.

Conclusion

Voilà !

May I have your attention please 🎤🎤

Feel free to subscribe here: www.rubycademy.com


Thank you for taking the time to read this post :-)

Feel free to 👏 and share this medium post if it has been useful for you.

Here is a link to my last post entitled Ruby Case Statement Behind the scene.

rubycademy

E-Learning platform for Ruby and Ruby on Rails

Mehdi Farsi

Written by

Founder of www.rubycademy.com — I blog about Ruby & ROR - Paris

rubycademy

E-Learning platform for Ruby and Ruby on Rails