Login Register


[Ruby] Refactoring filter_list
Author
Message
[Ruby] Refactoring #1
In Ruby, there's always more than one way to accomplish something. Some ways are cleaner, more efficient and faster than others, however.

Speed refactors:

If you have a lot of code, cutting down 1/100th of a second can add up. Here are some ways of speeding up your Ruby interpreter.

Hash Key lookups:
while setting keys in a hash, it's tempting to use a string or an integer. The better way to do this is with Symbols.
Code:
#slow hash = { "test_key" => "test value" } #fast hash = { :test_key => "test value" } #now if we look for the key using #the slow way hash.has_key?("test_key") #and the fast way hash.has_key?(:test_key) #the first way takes 0.02ish seconds, while the second takes 0.01

Cleanliness refactors:

I get really irritated when people make messy, hard to understand code. The following will help any new Ruby programmer with that.

Arrays:
If you need an array of sequential numbers or letters, you can use this trick:
Code:
#please don't (especially not the strings, if not needed) letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] #use this one letters = ("a".."z").to_a
The efficient way converts a Range to an Array with the .to_a method

Loops:
Cutting lines out from simple loops is one of the easiest tricks in the refactoring book. It works as follows.
Code:
alphabet = (:a..:z).to_a #remember this? #sloppy way alphabet.each do |letter| puts letter end #better way alphabet.each do { |letter| puts letter }

Conditional statements:
A huge if/elsif/else statement is a pain in the ass to sift through and is often an eyesore. A better way is to use case.
Code:
a = 0 #annoying if a == 0 puts "logic exists" elsif a == 1 puts "what the fuck?" else puts "I don't even know.." end #far more satisfying case a when 0 puts "logic exists" when 1 puts "what the fuck?" else puts "I don't even know.." end

If you just need "if", you can do the following:
Code:
a = 0 #please don't do this if a == 0 puts "logic is a thing." end #do this puts "logic is a thing." if a == 0 end


These are just a few examples of refactoring. Check out Stack Overflow or CodeCademy for more examples. And for fuck's sake, don't use the sloppy, lazy way.
Thanks!
-Touka
It's often the outcasts, the iconoclasts ... those who have the least to lose because they
don't have much in the first place, who feel the new currents and ride them the farthest.

[+] 1 user Likes Inori's post
Reply

RE: [Ruby] Refactoring #2
Thanks for the great tutorial, it sure helps out a lot! Biggrin


[Image: tumblr_noac9s6rgw1tvnnaxo1_500.gif]
Tik Tak~! Time is up~!

Reply







Users browsing this thread: