Main Content

Process every member of an array, and sort an array - Ruby

Archive - Originally posted on "The Horse's Mouth" - 2011-04-21 06:05:56 - Graham Ellis

If you're wanting to process every member of an array, you've a choice ... you can write a loop to step through the key of each member, you can write a loop to step through each member itself, or you can call a method which operates on the array as a whole (i.e. the loop is hidden within a method. As I've been teaching a Ruby course this week, I'll give you examples in Ruby.

• Using a loop through the indexes:

  for posn in 0...places.length
    puts "Have a break in #{places[posn]}"
  end


• Using a loop through the values:

  for place in places
    puts "Go to #{place} for a few days"
  end


• Using a builtin iterator / enumerator method:

  puts places.collect {|place| "Sand and sea in #{place}"}

What are the advantages and disadvantages?

Looping through the indexes is always available (in any language). The syntax is longer / it's more complex to write, but it's very flexible. If you need to make use of the key within the loop (and not just the value), this will be the one that you want. And for an ordered list if you want to look back to the previous item, or forward to the next one, then you'll want to use this.

It's shorter and neater code to loop through the values if you don't care about the position number within the array

And it's going to be faster to use a built-in iterator or enumerator such as collect or map. The loop is still there, but it's hidden within the language implementation itself so it should run much faster as well as being even shorter code.

Complete sample program - and sample output too - [here].




The same source code example shows array sorting in Ruby - both in a default form:

  places.sort!

and with a sort block specified, where you tell Ruby how to decide which of two elements comes first by passing it a comparator block:

  places.sort! {|left,right| left.length <=> right.length}

In both of these examples, I've used sort! rather than sort in order to alter the incoming array in situ - I didn't want a new, fresh copy as the original order was something I had no further use for. In the first half of the example, I could have used collect! rather than collect in order to modify the example in place, rather than create a fresh array.