Project Ramon

A learning journey from a Ruby noob perspective

Ruby Refactoring: Substitute Algorithm


Hello and happy Monday!

This week I’ll be resuming my review of Refactoring: Ruby Edition.

As we grow as programmers there will be times where we figure out easier ways to perform the same action. When this is the case, we should take time out to replace our older, more complicated code, and use our new found understanding to replace the old with our new, clearer way to accomplish the same goal.

Substitue Algorithm

Before we get into our brief example for today, here’s a peak at the mechanics to this refactoring pattern.


  • Prepare our alternative algorithm
  • Run this new algorithm against our tests, and if they pass then we’re done
  • If our test results aren’t the same then we can use our old algorithm to debug our new one


I like how the book’s example illustrates this:


def found_friends(people)
  friends = []
  people.each do |person|
    if(person == "Don")
      friends << "Don"
    if(person == "John")
      friends << "John"
    if(person == "Kent")
      friends << "Kent"

and after:

def found_friends(people) do |person|
    %w(Don John Kent).include?(person)


In addition to taking time out to replace our complex algorithm with something clearer, sometimes we may want to also change our algorithm to do something slightly different than before. In these cases it’s easier on us to substitute our algorithm first into something easier for the change we want to make.

We should also ensure that we have decomposed the method as much as we can.

This pattern reminds me of some great instruction about fixing my tic-tac-toe algorithm that I received from Marek Publicewicz.

IMO this is a good example of both clarity and debugging improvements to an algorithm I was working on at the time.

Stay tuned…


Categories: Ruby

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s