Arrays are a data type that allows you to store lists of data in your code. Data in an array can be sorted, reversed, extracted, and amended. You can also search through an array to find a specific value, and convert data within an array to another type of data.
In this guide, we are going to break down the most common Ruby array methods that you may want to use when you’re writing code.
Retrieving Items
In Ruby, arrays can be used to store a list of data. Arrays can include strings, numbers, objects, or any other type of data. If you had a list of employee names, for example, you may want to declare an array to store those names, rather than store them in separate variables.
Here is an example of how to create an array in Ruby:
employees = ["Hannah", "John", "Jose", "Kaitlin"]
Our array contains four names. However, when we call our array, we will be given all four of our names. So how do we get each one individually? Each of these names is given an index number, which we can use to access each value.
The first value in an array has the index number 0
, and each item counts up from that value. Here are the index values for our above array:
Hannah | John | Jose | Kaitlin |
0 | 1 | 2 | 3 |
So, if we wanted to get the second array object, we could use the following code:
print employees[1]
This would return John
, whose name has the position index value of 1
.
That is the basics of accessing elements from an array.
In addition, we can also retrieve multiple items from our array instead of a single element. In order to do so, we need to specify a range of elements that we want to get, using their index values. For example, if we want to get the elements with an index value between 1 and 3, we could use this code:
print employees[1,3]
Our code creates a new array with these elements, and returns the following:
["John", "Jose", "Kaitlin"]
The slice()
function also performs a similar task. If you want to get the values with index numbers between 1 and 3, you could use this code:
employees.slice(1,3)
Sorting an Array
Sorting data is a common operation in any programming language. For example, you may have a list of names that you would like sorted in alphabetical or reverse alphabetical order. Let’s break down how we can sort values in Ruby.
Reverse
The reverse
method allows us to reverse the order of the elements contained within an array. This can be useful if you already have an organized list of data that you want to be flipped into reverse order. Here is an example of the reverse
method being used:
employees = ["Hannah", "John", "Jose", "Kaitlin"] reversed = employees.reverse print reversed
Our code returns the following:
["Kaitlin", "Jose", "John", "Hannah"]
This function is useful if your array is already sorted, but what if your array is not sorted? That’s where the Ruby sort
method comes in.
Sort
Ruby’s sort
method allows you to sort data based on your needs. If we use the sort method without any parameters, we can sort a list in alphabetical order like so:
employees = ["Hannah", "Jose", "John", "Kaitlin"] sorted = employees.sort print sorted
Our program returns the following:
["Hannah", "John", "Jose", "Kaitlin"]
You can also specify your own sort algorithm if you have a specific sort in mind. Let’s say you want to sort your list in reverse order. You could use the following sort:
employees = ["Hannah", "Jose", "John", "Kaitlin"] sorted = employees.sort{|a,b| b <=> a} print sorted
Here is the result of our code:
["Kaitlin", "Jose", "John", "Hannah"]
As you can see, our code has reversed our list. There is a lot going on here, so let’s break it down.
The sort function performs a comparison between the objects in our array. The <=>
operator—also known as the spaceship operator—compares two objects and returns -1 if the object on the left is smaller, 0 if the objects are identical, and 1 if the object on the left is bigger. In the process, our code arranges our values based on the result of the operator.
It’s worth noting that our original array remains the same—sort did not modify the array—and our sorted array is stored in its own variable.
If we wanted to sort a list in ascending order, we would change our comparison like so:
employees = ["Hannah", "Jose", "John", "Kaitlin"] sorted = employees.sort{|a,b| a <=> b} print sorted
Our code returns the following:
["Hannah", "John", "Jose", "Kaitlin"]
Finding Array Items
There are a few Ruby functions that can be used to find array items: include, find, and select and reject.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
Include
In our code above, we were able to retrieve items by their index value. But what if we want to look for a specific item in our array? That’s where the include?
method comes in.
By using the include?
method, we are able to search through our array and find out whether it contains a particular value. Here is an example of the include?
method in action:
employees = ["Hannah", "John", "Jose", "Kaitlin"] employees.include? "Kaitlin"
Our code returns the following:
true
It’s worth noting that you can only use include to find whether an array includes an exact item. You cannot specify partial terms when you’re working with the include?
function.
Find
If you are looking to locate an element within an array, you can use the find?
function. The find?
method locates and returns the first element in an array that matches a certain condition that you specify. For example, let’s say you are looking to find the employee name that includes Jos
. Here is the code you would use:
employees = ["Hannah", "John", "Jose", "Kaitlin"] result = employees.find {|i| i.include?("Jos")} print result
Here is what our code returns:
Jose
Our program searched through the array to find any values that included Jos
, then returned the first one that matched our condition. The find?
function stops as soon as it finds the value we are searching for. And if a program does not find any values, it would return nil
.
Select and Reject
The select?
function can be used to find an item in an array as well. The main difference between select?
and find?
is that the select?
method returns a new array with the values that meet our criteria, whereas find?
only returns the first value that meets our criteria.
Here’s an example of the select method in action:
employees = ["Hannah", "John", "Jose", "Kaitlin"] result = employees.select {|i| i.include?("Jo")} print result
Our code returns the following:
["John", "Jose"]
Two values in our array—John and Jose—included Jo
, and so our program returned both of them.
Similarly, if we wanted to retrieve the values in an array that do not match our conditions, we can use the reject?
function. The reject?
method works in the same way as select?
, but returns all the values that do not meet our criteria. Here’s an example:
employees = ["Hannah", "John", "Jose", "Kaitlin"] result = employees.reject {|i| i.include?("o")} print result
Our code returns all of the names that do not include the letter o
, which are as follows:
["Hannah", "Kaitlin"]
Both select and reject return a new array and do not change the previous array.
Removing Duplicate Values
Often, when you’re working with a list, the list will contain duplicate values. This can be a problem because the more values your list has, the longer it will take your program to iterate through the list.
The uniq
array method can be used to remove duplicate elements from an array. Here’s an example:
["Alex", "Paul", "Katie", "Linda", "Alex"].uniq
Our code returns the following:
["Alex", "Paul", "Katie", "Linda"]
Reducing Arrays
When you’re working with an array, there may be a specific piece of information that you want to retrieve about the array. For example, you may want to get the total of values within an array. We can use the reduce
function to accomplish this goal.
Reduce iterates through an array and keeps a running total of the values we have added. The reduce function takes in one parameter: the starting value of the operation (this is 0
by default).
Here’s an example of the reduce function in action:
get_combined_age = [8, 16, 19].reduce(0) { | total, current | total += current } print get_combined_age
Our code produces the following result:
43
As you can see, the reduce function has added up the total value of every item in our array.
You can also use reduce to transform values within an array or perform another operation on those values. Here’s an example of a reduce function that will add one to each item in our array:
values = [1, 3, 5, 7, 9] new_values = values.reduce([]) do | array, cur | value = cur + 1 array.push(value) end print new_values
Our code adds one to each item within our array, and returns a new array:
[2, 4, 6, 8, 10]
Transforming Values
Let’s say you want to perform an operation on each element of your array. Perhaps you have a list of ages and you want to know how old everyone will be in five years. We can use the Ruby map
method to transform the contents of our array.
Here is an example of the map function in action:
ages = [8, 9, 12, 14, 18] in_five_years = ages.map{|i| i + 5} print in_five_years
Our code returns the following:
[13, 14, 17, 19, 23]
As you can see, our program has added five to each value in our array. While this may not be the most useful implementation of map
, there are many occasions where the function could be useful. For example, if you wanted to loop through a list of names and change them based on certain criteria, you could do so using the map
method.
Converting an Array to String
When you’re working with arrays, there may be a situation where you want an array to appear as a string. For example, if you have a list of property names for sale, you may want a user to see the list, rather than an array of items.
That’s where the join
method comes in. Join converts an array into a string, and gives you control over how the elements are combined. The join
method takes one argument: the character(s) that you want to use to separate the items within an array.
Here is an example of Ruby join in action:
employees = ["Hannah", "John", "Jose", "Kaitlin"] result = employees.join(", ") print result
Our code returns the following:
Hannah, John, Jose, Kaitlin
As you can see, our program has converted our array into a string and separated each value with a comma and a space. If we were to specify no separator, our array would still be converted into a string, but there would be no spaces:
employees = ["Hannah", "John", "Jose", "Kaitlin"] result = employees.join print result
Here is what our code returns:
HannahJohnJoseKaitlin
Conclusion
In this guide, we have broken down many of the most common Ruby array methods. We have explored how to retrieve information from an array, how to sort an array, how to transform data within an array, and more. These functions all have a wide variety of applications in Ruby.
Now you’re an expert at working with arrays in Ruby!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.