June 12, 2016

Parsing Exceptions in Ruby

One thing that is very subtle in Ruby that is an issue is how parsing works.  Say you have an Integer in C#, you would probably code something like this:

Int32.TryParse(value, out number);

But, if you look at Ruby, it is something like this:

def parse_integer(number) 
  Integer(number) 
rescue ArgumentError 
  nil 
end

While I could do the same logic in C# as in Ruby, the difference is the exception handling.  The problem is that throwing exceptions are way slower to handle.  Worse yet, it does not enforce trying to code as much as you can around exceptions.

I get it that Ruby is meant to get something up and running quickly.  But if we don’t have good practices like the tryparse function above, then we are writing slower code every time.

</end_rant>