Main Content

Ruby - examples of regular expressions, inheritance and polymorphism

Archive - Originally posted on "The Horse's Mouth" - 2010-10-02 07:44:35 - Graham Ellis

With delegates on public Well House Consultants courses staying in our on-site accommodation, there's time for them to learn a lot more about each other's applications and get a far wider view of the uses of the subject they're with us to learn. There's time for the delegate who wants to extend practicals to tryout some more code, and for delegates who would like the tutor to show them further examples.

On Friday, I was asked for further examples to illustrate polymorphism, and regular expressions in ruby, and to do so in an example which related to some practical use. Also to show a test harness / test cases in use.

The first examples - (see source) was a class for handling email addresses - with a test harness supplied too. The email addresses are initially split down into a user name and a domain, and then the domain is split down further into each domain level - so graham.ellis@sheepbingo.co.uk is split down to graham.ellis and sheepbingo.co.uk - which is then split down to sheepbingo, co and uk. This is a good reminder to not get involved with Matcho matching where the programmer tries to solve the whole problem with a single command / regular expresion!

I also wrote a server log analysis application - the regular expression was more complex here - and used four different classes for each server access; that's because I want to treat a success as a slightly different record to a failure, and split the failures between whether the failure was due to a server error or an error in the request. Of course, I didn't write four completely different classes - I simply wrote a single base class and then provided other classes that inherited from it, with only tiny bits of code in the subclasses which indicate the changes. See [here]. An extended version of that application - [here] - goes on to show how these classes of server access object are used and sorted to produce a list of the pages on our web site that were accessed in the last 24 hours, how many times, and from where.

P.S. These latter examples are interesting in that they also use a wholesale factory method - a static or class method which returns a whole array of new objects. There's more about factory methods [here].