lesson learned #432

lesson learned #432 (an error of omission)

the bug

Yesterday I introduced a "not so obvious" bug into my code. This particular bug took the form you see below.

It took a bit of searching Ruby docs and playing with the code to see the problem. It was an error of omission. File.open.readlines does exactly as expected and returns an array containing all of the lines in the file. Yes, but look what immediately follows that arrray. A block. The array returned by readlines calls no member methods. The block has nothing calling it so it does nothing. Unlike other languages, where blocks are just scope delineators, Ruby blocks are smarter. The block is not being asked to execute, so puts line never gets called.

the fix

The fix is extremely simple. Just ask the array to do something, like iterate over each element. Or even better call the each_line method and remove the need for readlines all together.

Sure this is somewhat trivial, but errors of omission, which do not throw exceptions or produce an error, are difficult to track down. This post serves as a reminder for me not to re-create this mistake. Was it self-indulgent? Sure, but aren't all blog posts?