Codewars: The First Kata
For those of you who are not aware, codewars is a website where you can test your coding skills against a range of challenges. It was described to me as the place to go after you are comfortable with the basic syntax of programming.
In other words, it was time to stop the spoon fed exercises.
My first ‘kata’, or exercise, involved a string (sentence) with a lot of nonsense words inbetween the real words. The example given was, ‘I AM X’ was transformed into ‘WUBWUBIWUBAMWUBWUBX’. Given the transformed, ‘WUB’ string, my job was to decode it to inout the original string.
My first real challenge came after I had successfully solved it and printed the ‘I AM X’ statement to the screen. The exercise kept throwing me a ‘not completed’ statement. Perplexed, I posted about my problem only for the comment to be ‘hidden’ within 5 minutes and I was linked to a specific bulletpoint within an article that stated my error was caused by printing and not returning the result.
Quickly googling (it’s a valid method, I swear) this I fixed my error and got my result. Hooray! Let me post my answer
It’s a bit of a monster but it does the job. However, my happiness was almost immediately deflated when, having solved this kata, I was given access to the solutions part of the site when I saw this:
Having no clue how this does what my method did in one line, I went to bed happy I’d atleast completed my first kata. Today, I have investigated what this one line solution does and have discovered:
Starting with the easiest to understand, the strip function removes whitespace at the beginning and end of the string.
(" hello world ").strip #transforms to "hello world"
Already, my solution can be written in one less line.
The second new function, gsub replaces all instances of the string (as opposed to sub, which just replaces it in that specific instance) and takes two arguments, what is to be found and what is to be replaced. It’s easier to think of it like Microsoft Word’s find and replace function and can be written like so:
But what’s going on with the /(WUB)+/ in their solution??
Apparently, /string/ is called a regular expression. How and why it is written inbetween brackets and not quote marks I don’t know. At the moment, I’m just thinking of it as quote marks — so (WUB)+ is the ‘find’ paramater.
(string)+ looks for all instances of string, including multiple ‘stringstringstring’. In this case, it treats both WUB and WUBWUB as the same thing. Looking at my answer, I replaced all instances of WUB with an empty space and then looked for two empty spaces next to each other and deleted the extra ones…
So as annoying and, shall we say, table flipping my rage was upon initially seeing this one line solution, I have learned from it and can hopefully take these methods to the next challenge.