Initiation by fire – part 1

1 Comment

Starting off as a Rails developer I ran into some problems coming from a Java/C++ background. Until Rails I more learned the languages for fun and something to play with in my free time, however by doing this I picked up some bad habits. I’ve worked with one of the top Ruby developers out there and learned to mimic his style and question his choices in code. I’ve learned a lot in the last year and a half I’ve been coding and now am even leading up a development team and teaching them the ins and the outs of Ruby.

Beginner mistake number 1:
For loops. I’m not so sure how the books teach it now but when I was initially learning Ruby all the books showed loops as

for item in collection

This is really easy to read, and will make developers from other languages feel a little more at ease with the language (it’s got the word for in there, and everyone knows what a for loop is). However you’ll quickly learn that using those for loops is really only for beginners. The real power of the for loop in rails doesn’t even have the word for in it. The real power comes from each.

collection.each do |item|

Not only is this also easy to read but it gives you so much more control over what you are doing. Want to pass in a counter variable? Simple

collection.each_with_index do |item, counter|

Or maybe you just want to get the keys from a group of hashes.

collection.each_key do |item_key|

There are many more possibilities, and by using each you are learning the style of what is probably the most powerful module in the Ruby language the enumerable module.

One Comment (+add yours?)

Leave a Reply