Copy, Paste, Learn

November 18, 2010

Since I started learning ruby on rails in order to build a program that I wanted to use, I spent a lot of time copying and pasting code that I didn't understand in order to produce the results I wanted quicker.  Of course, as soon as I ran into a bug, this habit bit me in the ass as I had to go back and learn what the copied code did in order to fix my bug.  And the bug always ended up being something debilitating that pissed off a user or two (which at the time was around half the user base).  Now, I know better.  I still copy code snippets (and use plugins) but I make sure I know what I'm copying and how it works.  I may not have known how to write it, but I can read it and explain it to myself (and in most cases, edit it without breaking it).

Today, I spent almost three hours chasing an issue that would have been fixed in moments if I followed my rule above.  I needed to remove spaces and other illegal characters from a string.  Not being a regex expert, I searched for the pattern I needed and found something along the lines of (simplified for the example) :

new_str = str.sub(/\W/,'_')

which worked fine or so I thought.  I knew about and have used "gsub" plenty of times before so when I saw the use of "sub" instead, I went to the ruby docs to sort out the difference.  I quickly glanced at the headings of the two different methods and found the following:

str.sub(pattern, replacement) => new_str
str.gsub(pattern, replacement) => new_str

Ah, so they're the same, I thought.  This seemed reasonable as I've seen other instance methods that are identical (eg. to_s and to_str), so I carried on.  Tested it out on a string with a space and it worked. Then, a user tried a string with three spaces in it and everything broke.  Of course, had I read the documentation closer I would have seen that "sub" only replaces the first occurrence of the pattern and "gsub" replaces every occurrence of the pattern.

The lesson here?  Well, I'm still far from being able to write everything I need without a little help from the google.  However, I need to pay better attention to the details of the code I didn't write myself.

Oh and here is the final result of what I was creating in the first place: