Fun With Ruby Arrays


One of the under-appreciated features of the ruby programming language is the excellent built-in array class. Arrays are one of the most common data structures, but arrays in ruby come with some neat benefits.

Since ruby has dynamic, weak types, ruby arrays are most easily thought of as a simple list of objects. Each element of the array is addressed by an index, which starts counting from 0. The default way of accessing the element at an index is with the [] method:

array = [1, 2, 3]
array[0] #=> 1
array[1] #=> 2
array[2] #=> 3

This is all standard programming fare. By default, ruby arrays return nil for nonexistent indices, instead of throwing an exception:

array[5] #=> nil

If you do not want to have nil returned, make use of the often-overlooked fetch method. Fetch lets you pass a value to be returned if the index is out of bounds, or pass a block that will be executed in that case:

array.fetch(5, 100) #=> 100
array.fetch(5) {|index| index\*100} #=> 500

For more fun, if you need to work with an array in reference to its last element, instead of its first element, you can just pass a negative index:

array[-1] #=> 3
array[-2] #=> 2
array[-3] #=> 1

This really useful: if you want the last character of a string in ruby, you can use a negative index like so:

hello = "Hello!"
hello[-1] #=> "!"

This is much more concise than the easiest way of doing the same thing in many other languages, for example Java:

String[] hello = {"H", "e", "l", "l", "o", "!"};
hello[hello.length() - 1]; //=> "!"

You can even use negative array indices with the useful ruby array range selection. The selection range still has to read ‘left to right’, so the lesser negative number comes first. You cannot wrap your selection around the zero.

array[1..2] #=> [2, 3]
array[-1..-2] #=> [] #incorrect
array[-2..-1] #=> [2,3] #correct
array[-1..1] #=> [] #probably not what you wanted

Of these methods, using the ruby array’s [-1] and .fetch are probably the most useful.

Get Notified of New Posts

* indicates required