cult3

Working with Arrays in Ruby

Apr 01, 2015

Table of contents:

  1. What is an Array?
  2. Accessing an element of an Array
  3. Inspecting an Array
  4. Adding elements
  5. Removing elements
  6. Iterating over each element
  7. Conclusion

Over the last couple of weeks we’ve started to get to grips with the Ruby programming language.

We looked at some of the reasons why you would want to learn Ruby as well as how to install and play around with IRB in Getting started with Ruby.

Next we looked at using the String object and some of the useful methods that are available to us in Working with strings in Ruby.

This week we’re going to be looking at the Array object.

What is an Array?

Before we look at the Array Ruby object and the methods that we have available, first its important to understand what an Array is and what they are used for.

An Array is a data structure consisting of a collection of elements (values or variables), each identified by an index.

The first element of the Array has an index of 0, and each subsequent element has a sequentially increasing integer index.

An example of creating an array in Ruby would be:

colours = %w[red blue green]
# => ["red", "blue", "green"]

Arrays in Ruby are very useful when you need to work with a collection of items that you don’t really care about accessing each element by a key, but you do care about the order of the elements.

Accessing an element of an Array

You can access an element of the array by selecting the element at the specific index using square brackets:

puts colours[0]
# => "red"

You can also pass in a start position and a length to retrieve a certain section of an array:

colours[1, 2]
# => ["blue", "green"]

Or a range of elements:

colours[1..2]
# => ["blue", "green"]

Alternatively you can get the first or last items by calling the first or last helper methods:

colours.first
# => "red"

colours.last
# => "green"

You can get the first n elements with the take method:

colours.take(2)
# => ["red", "blue"]

Or the elements remaining after the n elements have been dropped:

colours.drop(2)
# => ["green"]

Inspecting an Array

When working with an array, you will often find yourself needing to inspect it’s elements.

Luckily there are a few methods for doing just that.

chipmunks = %w[alvin simon theodore]
# => ["alvin", "simon", "theodore"]

To count the number of items in the array you can use either the count, length or size methods:

chipmunks.count
# => 3

If you need to check to see if the array is empty, you can use the empty? method:

chipmunks.empty?
# => false

And if you need to check to see if an array contains a particular element, you can use the include? method:

chipmunks.include?('alvin')
# => true

Adding elements

When you have an collection of items, you will often want to add or remove items from the Array.

To add an element to the end of an Array you can use either push or the << operator:

items = []

items.push('one')
# => ["one"]

items << 'two'
# => ["one", "two"]

The unshift method allows you to add an item to the start of an array:

items.unshift('zero')
# => ["zero", "one", "two"]

And finally the insert method allows you to insert an item at a particular index:

items.insert(2, 'hello')
# => ["zero", "one", "hello", "two"]

Removing elements

To remove the last item of an Array and return it, you can use the pop method:

items = %w[one two three]

items.pop
# => "three"

Alternatively, to remove and return the first element of an Array, you can use the shift method:

items.shift
# => "one"

If you want to delete an element at a particular index you can call the delete_at method:

items = %w[one two three]

items.delete_at(1)

Or if you want to delete an element by it’s value, you can simply use the delete method:

items.delete('three')

A common problem that arrises is when you have an Array, but the Array contains nil items. This can cause all sorts of problems.

To remove nil items from an Array, you can use the compact method:

items = ['one', nil, 'two', 'three']

items.compact
# => ["one", "two", "three"]

Another useful method is removing duplicate elements using the uniq method:

items = %w[one one two three]

items.uniq
# => ["one", "two", "three"]

Iterating over each element

When you are working with a collection of items as an Array, it will be inevitable that you will want to iterate over the collection to do something with each item.

There are a few ways of doing this in Ruby.

Firstly, we have the each method that accepts a block:

people = %w[Home Marge Bart Lisa Maggie]

people.each { |person| puts person + ' Simpson' }
# Home Simpson
# Marge Simpson
# Bart Simpson
# Lisa Simpson
# Maggie Simpson
# => ["Home", "Marge", "Bart", "Lisa", "Maggie"]

If you don’t know what a block is, don’t worry, we will be covering them in a future tutorial.

Alternatively we have the map method that creates a new array from the values that are returned from the block:

people.map { |person| person + ' Simpson' }
# => ["Home Simpson", "Marge Simpson", "Bart Simpson", "Lisa Simpson", "Maggie Simpson"]

If you want to only select certain items from an Array that match a condition, you can use the select method and pass it a block:

people.select { |person| person.start_with?('M') }
# => ["Marge", "Maggie"]

Conclusion

Arrays are one of the fundamental building blocks of just about every programming language.

Arrays are really useful for working with a collection of items when you don’t need to identify each element of the collection with a specific key.

Arrays are also really useful when you care about the order of a particular collection of elements.

Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.