Handling Strings Part 1 - String Parsing
Using Regex and The Rails Framework
I have been working on this post for months. One of Ruby's strengths is it string handling but working on a live system which processes lots of string inputs of varying types, requirements and potential pitfalls.
Part 1 - String Parsing
The first part of this post series focuses on processing strings for logic and fun. In many cases you may need to determine if a string is actually a number of some kind.
In many cases that would be checking that the string is an integer. The usual way of checking this in a bunch of languages I have used is to attempt to parse the string as an Integer
or equivalent class and catch any exceptions.
This can be computationally costly and is considered an anti-pattern in some circles. The pattern implies two computational tasks, the parsing of the class and then wither the return true or the catch and return statements which affect the conditional.
Another issue (which is what I encountered) was that Im processing floating numbers and integers as strings - In which case both will return true as a Float
using this pattern but when looking for an Integer
will raise an exception.
My solution was to use REGEX
which has appeared to work really well.
Another parsing issue I recently ran into was generating a slug
or unique string identifier from a user inputted string field. This was to add this identifier to a database table after the fact.
I worked on a method that was first created by a colleague of mine for an almost exact use case - but in a different part of the codebase. There are many weird cases and my addition to the method was to just make it more robust to duplication and handling nil
.
Its mostly a nest of ruby/rails string method calls and could be easily optimised and cleaned up into a lot less method calls and fewer REGEX
but it is used in low operation use cases and the slug is then used by database SQL
statements so performance was not a priority here.