Often people approaching Ruby (because approaching Rails first…) ask me some feedback on their code, that looks like that:

# array of things
a = [1, 2, 3, 4]
for i in a
  # do something with "a" elements

Every time we traverse an array is because we just want to:

  • find a particular element and do something with it
  • apply a “transformation” to all array elements
  • slice the array

Thankfully Ruby has a lot of goodies when dealing with array (or with Enumerable(s)…). Let’s see some of them.

The first form of traversing is the well-know method each:

a.each {|item| # do something with item }

but we can be more explicit about what we really want to do within the array:

a.select {|i| i > 2} # => [3, 4]
a.reject {|i| i > 2} # => [1, 2]

In practice, the select method returns only the array items that satisfy the predicate inside the block (i > 2). Similarly the reject method has the opposite effect. Obviously the select! and reject! variants operate directly on the array.

With detect and its synonym find it’s possible to search for the 1st element that satisfy some criteria (or use find_all if need it):

a.detect {|i| i % 2 == 0} # => 2
a.find {|i| i % 2 == 0} # => 2

Other useful method used when we want to apply a transformation to every element of the array is map and its synonym collect:

a.collect {|i| i*i} # => [1, 4, 9, 16]
a.map {|i| i*i} # => [1, 4, 9, 16]

Again, we have the map! variants.

Finally, a “strange” method that enables us to do a lot of interesting things on arrays. inject mathod is simple and powerful: it traverses the array, giving to each step an “accumulator” variable (eventually initialized). See some example:

a.inject {|acc, i| acc + i} # => 10
a.inject(10) {|acc, i| acc + i} # => 20
a.inject([]) {|acc, i| acc << 10*i} # => [10, 20, 30, 40]

The most important thing to remember is that code is communication. Communication from you to your code pals and/or colleagues; communication from you to yourself when you’ll read your code in next two months (or maybe less…). So let’s try always to be more clear as possible, always make evidence of our intents when coding.


Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Spam protection by WP Captcha-Free