Refactoring of the week

Since last week I pushed a whole lot of new features to RefactorMyCode:

  • Email notification when a new refactoring is posted
  • Edit your refactoring
  • More caching to make page loading über fast
  • Make popular page sort by week first, so old stuff doesn’t stay on top
  • Add an alternative OpenID in case your main one is down (set it in your account page)

One of the most popular code this week was posted by Frank Lamontagne from Ruby Fleebie and TimmyOnTime. He cross posted his last edition of the famous Rubyize this to RmC while using the trackback feature (allowing to send a trackback to your blog on each refactoring being made on the code). The idea of a Rubyize this is that he post a code that is poorly written on purpose and ask his readers to refactor it. Seeing the success of the 2 first editions was a trigger in my idea of building RmC. The results are always amazing in quality and diversity.

Here’s the code he posted:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def remove_insults(input)
   ctr = 0
   input.each do |word|
     word = word.downcase
     if word == "stupid" || word == "moron" || word == "dumbass" || word == "retard"
       i=0
       word.length.times do
          input[ctr][i,1] = "*"
          i+=1
       end
     end
     ctr += 1
   end

   puts input.join(" ").to_s
end

remove_insults "you truly are a moron sir!".split(" ")

Small_logo

Ugly no?

Not anymore, thanks to Jorel, Frank, Scott, Daniel and hungryblank who refactored it to:

1
2
3
4
5
def remove_insults(sentence)
  sentence.gsub(/stupid|moron|dumbass|retard/i) { |insult| '*' * insult.size }
end

puts remove_insults("you truly are a 'Stupid' moron, stupid sir!")

Shorter, faster, better! No this is not a Kanye West song, it’s beautiful code!

Leave a comment

Filed under refactormycode, ruby

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s