Dan Ahern

12 Oct, 2007

Initiation by fire – part 1

Posted by: admin In: ruby

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.

Bookmark and Share

1 Response to "Initiation by fire – part 1"

1 | Dan on Rails at Powered By Geek

October 13th, 2007 at 2:48 am

Avatar

[...] Click Here for the full article.  [...]

Comment Form


  • danahern: Oops, you're absolutely right. I copied the wrong code and didn't change it over. Thanks for pointing that out. Great toolkit by the way, I'm reall
  • Nicolas: Hi, very useful article, thanks :) I was wondering if in the last code snippet the JQuery expression: $(domElement).set('html', node.name + " an
  • Will Harris: Damn, who wrote this? Good stuff. Good luck in your transformation!

Flickr PhotoStream

    DSC_0082.jpgDSC_0071.jpgDSC_0079.jpgfirst_hdr copy

About

By day, I'm the Lead Developer for a small startup. By night, I'm writing social applications and managing development for Powered By Geek.You can find me: