Become a Code Ninja with Codewars

I am not a ninja, in the traditional sense. My chubby frame and fuzzy beard can attest to that. But Codewars has given me the ability to be a ninja in one very special area of my life: programming.

Kata are moves that one practices and perfects as they attempt to master a martial art. In this spirit, Codewars presents you with hundreds of kata (coding challenges) in the programming language of your choice. As you earn honor points for completing kata, you advance through the “kyu” (ranks).

The concept of programming kata has been around in other forms, but Codewars is an entire platform of crowd-sourced programming challenges. Users are encouraged to create kata of their own that are curated and used by others. It’s a self-perpetuating system (with a lot of hard work from the Codewars staff).

Each kata has a description, a browser-based code editor, and even a small testing library you can use to verify your own solutions. Once you’re confident you’ve solved the kata, you can submit your code to see if it passes the kata author’s own set of tests. Instant gratification!

kata

Why Train?

As I said earlier, programming kata is not a new concept. Years ago, Chad Fowler published a book that stressed the importance of practicing your programming craft. Chad posed an interesting question: you wouldn’t expect to become a great musician with all performance and no practice, so why do we think we can become great developers without challenging ourselves outside of work?

Malcolm Gladwell explored the concept of “10,000 hours” in his book Outliers. The theory is that it takes about 10,000 hours of dedicated practice to become an expert at something. If you’re like most developers, 90% of what you do at work doesn’t count.

Becoming an expert requires constant challenge, and that’s what Codewars provides. They gamify the act of self-improvement, and they do it well – it’s downright addictive!

 

 

Programming Kata: Treat a Hash Like a JavaScript Object

In JavaScript, objects look and act an awful lot like hashes:

var hash = {a: 'b', c: 'd'}

hash.a  #=> 'b'
hash['c']  #=> 'd'

How can we mimic this in Ruby? It’s easier than you might think. Ruby classes have an instance method called `method_missing` that is called whenever…you guessed it…it can’t find the method you asked for. Since Ruby allows us to open up any class and extend it, let’s do that now:

class Hash
  def method_missing method_name, *args, &block
    return self[method_name] if has_key?(method_name)
    return self[$1.to_sym] = args[0] if method_name.to_s =~ /^(.*)=$/
    
    super
  end
end

Now we have JavaScript object-like power in Ruby hashes:

hash = {:five => 5, :ten => 10}
hash.five  #=> 5
    
hash.fifteen = 15
hash[:fifteen]  #=> 15

We’re doing three things here. First, we’re checking if the hash has a key by the given method name (as a symbol). If it does, we return the value. Next, if method_name ends in an equal sign, we create a new hash entry with the value specified. Finally, it’s very important to always call `super` at the end of `method_missing`. This way, if the method is still missing, other parents classes up the inheritance chain might provide the solution.

You can practice this as an interactive kata on Codewars.

Rubyists Should Learn from Ford’s Example

From the moment I laid my twelve year old eyes on the Ford Mustang, I was in love. But even before that, I remember taking road trips to Wisconsin, bouncing around in the covered bed of my dad’s F-150 pickup with my sister. Back then, we didn’t wear seat belts – my parents would lay down a mattress for us to play on in the back, while they enjoyed the eight-hour journey in relative peace and quiet up front.

I’ve been a Ford guy all my life. But in the 90’s, a disturbing trend began. Ford, and indeed most auto makers, started homogenizing their product lines.  As the “curvy design” fad erupted, Mustangs were redesigned to look more like the Taurus. And F-150’s were redesigned to look more like…the Taurus. I hope they saved a lot of money on design work, because everything had the same oval headlights and curved hood. Each model was trying to be everything to everyone.

Just when all looked lost, Ford came to its senses in the 2000’s. They started designing the cars so people actually knew what they were for. The mustang now looks like a muscle car:

mustangs

The Fusion, which evolved from the Mercury Milan, now looks sporty, but efficient:

mid-sedans

The Five-Hundred (which looks better in person) boasted size, style, and luxury:

full-sedans

And finally, the F-150 now looks like the workhorse it was meant to be:

trucks

Rubyists Can Learn from Ford

First, show intent. While code comments can be helpful, they can also be a crutch. Ruby is a wonderfully expressive language, so use it. Spend time naming your classes, modules, methods, and variables with the intent of having them be perfectly understandable to a stranger. When a method has several parameters, wrap them in a hash so developers (yourself included) can better understand what a method call is trying to accomplish. As a bonus, you won’t have to look up the parameter order every time you want to use the method.

Keep your methods small, and remember the old mantra: a method should do one thing, and do it well. But don’t stop there. Controllers shouldn’t be stuffed with dozens of actions; you probably need more controllers that each handle a more specific part of your application.

On a larger scale, don’t limit yourself to just one app. If your company or project is doing lots of different things, it may need several different apps. They can still talk to the same databases when they need to, and they can appear seamless to a site visitor.

Businesses Can Learn from Ford

A lot of businesses also make the mistake of trying to be everything to everyone. I see this a lot with consulting companies in my own industry. In order to cast the widest net, dev shops will take on any type of work, that uses any programming language or technology they have experience with. Sometimes they might not even have that experience, and that’s usually good news for me. Rescue projects are a big part of my business.

I’ve chosen to focus on the Ruby programming language, and I put my money where my mouth is when I chose my business name. That doesn’t mean I stop learning other technologies. It means that I choose to invest my limited time learning the technologies that will make me a better Ruby developer. Currently I’m digging into PostgreSQL, because it has so much more power than just database queries, and this will improve the performance of my Ruby applications. I also have several years of Perl experience, but I choose not to take on Perl contracts.

RubyCuts is relatively new. During the toddler stage, I’m more open to taking on lots of different types of projects. As we grow, we will focus more and more on our core – training, scaling, and rescue. Lots of developers can build basic applications in Ruby, but I want RubyCuts to be the Navy Seals of the Ruby world. I want to help companies solve the toughest problems so their dev team can get back to building money-making features. I want to make it as easy as possible for companies to invest in Ruby.

I think the future of small business is in specialization, solving very specific problems. The trick will be picking the highest value problems to solve. As Ruby gains popularity, I think the increased number of beginners will require an increase in experts. If I’m not successful in five years, you have my full permission to rub this article in my face 🙂

 

 

All I Need to Know about Business, I Learned on StackOverflow

I recently ran across this light-hearted post on StackOverflow. If you’re not familiar with StackOverflow, it’s a question/answer site for programmers. Users gain reputation points for answering questions from other users, and it can be addictive to grow your reputation over time. I’m in the top 3% of StackOverflow users, myself.

Based on the principal that 10% of the world’s population owns 90% of the wealth, one user wanted to see  how much of the total reputation points were “owned” by the top 10% of users. His initial calculations showed that 95% of all reputation points belonged to this group! It wasn’t long before people started cracking jokes about our economy:

stack overflow reputation comment

and:

stackoverflow reputation answer

Of course, the national/global economy and the StackOverflow economy are two very different things, and I’m not trying to trivialize some very tough problems the U.S. faces. But there’s still a nugget of wisdom here. While reputation points do offer some benefits on the site, they are not “spent”, per se. So your reputation is really a measure of the value you’ve generated.

If you apply this principle to your business endeavors, you might be amazed at how well it works. As a contract Ruby developer over the last seven years, I’ve learned that my success is closely tied to the value I generate for others. I’m not just talking about doing a good job for my clients, though that comes first. I do a lot of things I don’t get paid for, directly:

  • I speak at local Ruby events.
  • I’ve co-organized both the Kansas City and Lincoln, NE ruby meetups.
  • I answer a lot of Ruby questions on Stack Overflow.
  • I’ve contributed to open source projects, including Ruby on Rails itself.
  • When I don’t have the availability to take on new clients, I refer them to other good developers I know.

These things have been very rewarding on their own, but have they “paid off” in real dollars? Absolutely. Fellow Rubyists refer work to me, because I have a good reputation.  One client skipped the first half of their interview process entirely, based on my contributions to Rails. And yes, being a “3-percenter” on StackOverflow has given clients the confidence to trust my expertise.

My advice to any up-and-coming developers is always the same: look for ways to generate value, whether they pay directly or not. If you’re a contractor, you’ll benefit in many of the same ways I do. If you’re a recent college grad, your open source contributions and public speaking will say more about your ambition and talent than your GPA.

In fact, generating value should be the top priority of every business. That’s why the best mission statements tell people what value you provide, not what things you sell. We all like dollars. What sets you apart in business is how valuable you are to the world.

Enumerable Magic – Introduction

Whether you realize it or not, you get a lot of use out of Ruby's Enumerable module. It shows up in arrays, hashes, file I/O, database interactions, and more. I'm going to explain what this module is, and how you can put it to use in your own Ruby classes.

What is a Module, and what is the Enumerable Module Specifically?

In Ruby, a module is a collection of methods, constants, and variables that can be included in classes to extend their functionality. The Enumerable module is responsible for a lot of the power behind arrays and hashes. If you've ever used methods like map, select, or count on an array, you weren't using methods built into the Array class itself - they were mixed in from Enumerable!

Here is the simplest version of a class which includes the Enumerable module:

class List
  include Enumerable

  def initialize
    @items = []
  end

  def each
    @items.each{|item| yield item}
  end
end

We start by including the Enumerable method. Then we provide an each method which all the Enumerable methods will use to iterate over the items in our list. While this example uses an each within an each, you don't have to. We can accomplish the same thing with successive yield calls in our each method. You can see this in an abbreviated version of the PetInventory class included with this lesson's source code:

# full source: https://github.com/rubycuts/enumerables/blob/master/lib/pet_inventory.rb

class PetInventory
  include Enumerable
  
  def initialize
    @dogs = Pet.new('dog', 4, 100)
    @cats = Pet.new('cat', 4, 50)
    @fish = Pet.new('fish', 0, 1000)
  end
  
  def each
    yield @dogs
    yield @cats
    yield @fish
  end
end

Calling yield three times in our each method means that any Enumerable methods will treat our PetInventory object as a collection with three items - a dog, a cat, and a fish.

This example also illustrates another good point. We were sort of cheating in our first example. Since @items is an array, it already has the enumerable methods available - no need to wrap it in the List class. In real life, almost every time you have a collection class, it's going to be a container for a groups of another class you've created. In this case, PetInventory is managing a collection of Pet objects.

Using Enumerable Methods

One of the easiest Enumerable methods to understand is sort_by. It will sort an enumerable collection based on the formula you give it. We'll use this method to illustrate the two main ways you will call most Enumerable methods. First, the long way:

pets = ['rooster', 'dog', 'fish']

# sort by pet name length
pets.sort_by{|pet| pet.length}  #=> ['dog', 'fish', 'rooster']

# sort by third letter in name
pets.sort_by{|pet| pet[2]}      #=> ['dog', 'rooster', 'fish']

We pass sort_by a block that will be run on each item in the list, and the list will be sorted based on the outcome. When the block will call a simple method on the object, as in the case of pet.length, there is a shorthand way to write this:

pets.sort_by(&:length)

This only works with simple methods that require no arguments, but you'd be surprised how often this is the case. Notice we couldn't sort by third letter using this shortcut, because that's a more complicated formula.

What Else?

Learning the Enumerable module will give you merlin-level powers over simple Hashes and Arrays, but learning to use Enumerable in your own classes will make you...whatever level wizard is three slots above merlin.

At first you might be hard pressed to think of places to use it, but it shows up more than you think. Ruby's File class allows you to iterate over each line in a file as if it was an Array, thanks to Enumerable. Many database wrappers do the same for select queries. In my example code, I flesh out a basic LogData class that iterates through Heroku logs so you can work with them without needing to load the entire log file into memory at once.

Like any great tool, once you start looking, you'll find more uses. I've just given you a hammer, and there's a world full of nails out there. Enjoy!