1. Computing

Basic Array Operations

By

Basic Array Operations

Beyond creating Arrays with literals, indexing the elements and iterating over the elements, there are a lot of very useful things that can be done with Arrays. These are a few of the base operations you'll be using with Arrays, things that you'll keep coming back to time and time again. While it may not sound important at first, learning the Array operations can make your life much easier in the future.

Building Arrays at Runtime

In the previous examples, Arrays were created using Array literals. This is fine, but only if you know what the contents of the Array should be when the program is being written, and this is rarely the case. In this case, an empty Array can be created (either using Array.new or the empty Array literal) and elements pushed or appended to the end of the Array.

There are two ways to do this. The first is the push method, which is functionally equivalent to the oft-used "append" operator <<. This is probably the easiest and fastest way to accomplish this task since it appends to the Array in place, and doesn't create any new Array objects. In the following example, an Array is created and strings are read from the keyboard until the "end" string is read, each string is appended to the Array.


#!/usr/bin/env ruby

names = []
puts "Enter names:"

loop do
	name = gets.chomp
	break if name == 'end'
	names << name
	# Same as  names.push(name)
end

puts names.inspect
Enter names:
Alice
Bob
end
["Alice", "Bob"]

The second way to build Arrays is to the split strings. The split method on a string splits the strings into substrings and returns an array of them. This is particularly useful on things like comma-separated data. For more information on this, see the articles on coding a CSV parser in Ruby.

Sorting Arrays

Ordered data is often most useful when sorted. Imagine reading in a giant list of names, sorting them and iterating over them in alphabetical order. Or, perhaps more tangibly, each object representing an email in an email client and, as the user clicks on the sort buttons in the UI, the Array is sorted in various ways (by date, or sender, or subject, etc). This is so common, you often only need to use a single method call with no arguments, the sort method.

How this works gets a bit complicated. In order for objects to be sorted meaningfully, the objects must implement the "spaceship" operator <=>. All of the base types have done this already, so things like strings will sort alphabetically, numerics numerically, etc. So let's get a list of names and sort them.


#!/usr/bin/env ruby

names = []
puts "Enter names:"

loop do
	name = gets.chomp
	break if name == 'end'
	names << name
	# Same as  names.push(name)
end

names = names.sort
# Alternatively, use names.sort!

puts names.inspect

Now, if you were to input Bob, then Alice, since the names are sorted before they're printed, it would still print Alice before Bob. Take note of the names = names.sort line, because if this is the only code that uses the names object, then this line should probably read names.sort!. Note the exclamation point. The exclamation point at the end of a method name is a Ruby idiom, an ad hoc rule that simply means "harder." In this case, it means to sort the Array in place, and not to create a second Array object. Using methods like this can actually improve the performance of programs, so if it makes sense to sort the names in place and not create a second Array object if it's not needed.

Set Operations

Set operations, things like union and intersection, are possible and very simple with Arrays in Ruby. Imagine the following situation, you're given a list of all students in a class. You're then given a list of the students that failed the class, and you need a list of students the passed. All that's really needed to be done here is to subtract the failed students from the student list (also known as the set difference). This is done in Ruby in a remarkably simple way: subtracting one Array from the other.

Remember that operators can be overwritten in Ruby. Assuming arr1 and arr2 are Array objects and we evaluate arr1 - arr2, what will happen is a third Array will be created that will have all of the objects in arr1 that are not in arr2. Let's see this in practice.


students = %w{ Alice Bob Carol Dave }
failed = %w{ Bob Dave }
passed = students - failed
puts passed.inspect  # Alice and Carol will be printed

As you can see, the passed = students - failed statement describes the problem succinctly and clearly. If you were to encounter this without knowing about the set operations, it's likely you would surmise its purpose and function without any further explanation.

©2014 About.com. All rights reserved.