Getting Started with Arrays in Ruby

Arrays are one of the most important & popular data structures in ruby, working with & understanding how arrays work is vital to developing web applications. Arrays allow’s you to store data as a list of elements(objects). The elements do not have to be the same object type they can be any element, even another array.


How to create an Array

An array can be created in multiple ways here are a few examples.

An array can be created with square brackets

["a", "b", "c", 1, 2, 3]

You can also create an array using the new method.

Array.new # => [] creates an empty array when no arguments are specified.
Array.new(2, "a") # => ["a", "a"] The first argument specifies the number of items in the array, the second argument is used to populate the array

How to access elements in an Array

Each element in an array has an index position, and it’s a bit tricky to get when you first start working with arrays. The first element in an array has the index of 0. There are a few methods you can use to access elements in array, [], slice, fetch and at. You can also use negative indexes to access an array from the last element -1 or second to last -2. Ruby being a very programmer friendly language made it east to access the first(index 0) and last(index -1) elements in a array using the methods first and last .

my_array = ["a", "b", "c", 1, 2, 3]
my_array[0] # => "a"
my_array.slice(2) #=> "c"
my_array.fetch(5) #=> 3
my_array.at(1) #=> "b"
my_array.first #=> "a"
my_array.last #=> 3

Fetch is different from all the other methods and can come in quite handy at times. If you were to try and access and index that doesn't exist with any other method it would return nil but with fetch you can add a second argument and return an error message.

my_array = ["a", "b", "c", 1, 2, 3]
my_array.fetch(10, "This array ends at index #{my_array.length-1}") # This array ends at index 5
my_array.fetch(10) #IndexError: index 10 outside of array bounds: -6...6

Working with multiple elements in an Array

Sometimes you need more than one element in an array, ruby has a few options for retrieving multiple elements.

You can either specify a start and end index, or a range.

my_array = ["a", "b", "c", 1, 2, 3]
my_array.[1, 4] # => ["b", 2]
my_array.[1..4] # => ["b", "c", 1, 2]
includes both indexes
my_array.[1...4] # => ["b", "c", 1] Does not include last index

The values_at method is used to retrieve single or multiple elements.

my_array = ["a", "b", "c", 1, 2, 3]
my_array.values_at(1, 4, 0, 3) # => ["b", 2, "a", 1]
my_array.values_at(1) # => ["b"]

The take method is used the retrieve the first n number of elements .take(n)

my_array = ["a", "b", "c", 1, 2, 3]
my_array.take(3) # => ["a", "b", "c"]
my_array.take(2) # => ["a", "b"]

The drop method starts at the index provided and gives you the rest of the elements .drop(n)

my_array = ["a", "b", "c", 1, 2, 3]
my_array.drop(3) # => [1, 2, 3]
my_array.drop(2) # => ["c", 1, 2, 3]

The length count & size methods in an array.

The methods are used on an array to get the total number of elements inside that array. Arrays start with the index of 0 but these methods start counting from 1. count is a bit more flexible and if provided with an argument(n) it can count the number(n) in the array.

my_array = ["a", "a", "b", "c", 1, 2, 3]
my_array.length # => 6
my_array.size # => 6
my_array.count # => 6
my_array.count("a") # => 2

Check if values exist or array is empty

Predicate methods are methods that end with a question mark(?) and return true or false . To check if an array is empty would call either .empty? . But there are of-course a few different ways to explore if an item is in an array we did a few previously.

my_array = ["a", "a", "b", "c", 1, 2, 3]
my_array_1 = []
my_array_1.empty? # => true
my_array.empty? # => false
my_array.any? {|n| n == "a"} # => true
my_array.include?(2) # => true
my_array.any? {|n| n == "f"} # => false
my_array.include?(5) # => false

Appending an element to an Array

Adding an element to the end of an existing Array you can be done by using the operator <<, called “shovel operator”, the push methord or insert . Insert takes a minimum of two arguments the first being the index position you would like to start inserting elements into the array, the second the element you would like inserted.

my_array = ["a", "b", "c", 1, 2, 3]
my_array << "d"# => ["a", "b", "c", 1, 2, 3, "d"]
my_array.push(4) # => ["a", "b", "c", 1, 2, 3, "d", 4]
my_array.insert(3, "new item")# => ["a", "b", "c", "new item", 1, 2, 3, "d", 4]

Nested Arrays

Nested arrays are very common and useful in ruby especially when working with tables & data structures. If you have a spreadsheet of nested arrays is how you would go about representing that data. The outer Array represents the table, and each inner Array represents one row. Each value then represents a cell.

[
["a", "b", "c"],
[1, 2, 3],
[4, 5, 6],
[0]
]

Conclusion

Arrays have lots more methods that you can explore in the Ruby documentation. In my journey of learning to code with ruby I’ve had some difficulties with arrays. But after practicing and working on solving code challenges and reading up on arrays I’ve become more comfortable with them. And also have a bit more insight how how powerful they are. Thanks for taking the time to read my article hopefully you took something away from it.

Also feel free to connect with me via my linkedIn or github pages!